Functions

Learn how to use functions in Solidity.

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.

Press + to interact
How functions work
How functions work

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
}
Function declaration syntax

Let’s look at a simple function declaration example.

Press + to interact
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Storage {
//Declaring state variable of uint type
uint256 public number;
constructor(){
//Initializing the state varibale
number = 1;
}
//Declaring a function to increment a value
function getIncrementedNumber() public view returns(uint)
{
//Local variable nonce
uint nonce = number + 1;
return nonce;
}
}
  • Line 3: We declare a contract named Storage.

  • Line 5: We declare a state variable named number of the uint256 type with the public visibility specifier. This means it can be accessed from outside the contract.

  • ...