Functions
Learn how to use functions in Solidity.
We'll cover the following...
A function is a collection of reusable code that can be invoked from anywhere in the application. This avoids the need to write the same code again and over. It aids programmers in the creation of modular code. A programmer can use functions to break an extensive program into several tiny and manageable functions.
Solidity, like any other modern programming language, has all of the functionality required to construct modular programs using functions. This section introduces how to create Solidity functions.
Declaring a function
We must declare a function before we can utilize it. The function
keyword—followed by a unique function name, a list of arguments (which can be empty), and a statement block enclosed by curly brackets—is the most popular way to construct a function in Solidity, as shown below.
function <function_name>(<parameter-list>) <scope> returns() {//Code to execute}
Let’s look at a simple function declaration example.
// SPDX-License-Identifier: MITpragma solidity ^0.8.17;contract Storage {//Declaring state variable of uint typeuint256 public number;constructor(){//Initializing the state varibalenumber = 1;}//Declaring a function to increment a valuefunction getIncrementedNumber() public view returns(uint){//Local variable nonceuint nonce = number + 1;return nonce;}}
Line 3: We declare a contract named
Storage
.Line 5: We declare a state variable named
number
of theuint256
type with thepublic
visibility specifier. This means it can be accessed from outside the contract....