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.
Line 3: We declare a contract named
Storage.Line 5: We declare a state variable named
numberof theuint256type with thepublicvisibility specifier. This means it can be accessed from outside the contract.Lines 7–10: We define the
constructor()function. It initializes thenumberstate variable with the value1when the contract is deployed. ...