Open In App

Solidity Local Variables

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Local variables in Solidity are defined within functions or code blocks. They are only available inside that function or block and deleted when that scope ends. They hold temporary data that is only relevant inside a function or block of code. They may store intermediate computations, data, or function return values.

Solidity local variables need data types. Local variables in Solidity are usually uint (unsigned integer), bool (boolean), string, or address (Ethereum address). Local variables may only be accessed inside their specified function or block of code. This helps structure your code and avoid variable name conflicts.

Example 1

Below is the Solidity program to calculate the sum of two integers using a local variable.

Solidity




// Solidity program to calculate the 
// sum of two integers using a local variable.
pragma solidity ^0.8.0;
  
contract LocalVariableExample {
    
  function add(uint256 a, uint256 b) public pure returns (uint256) {
      
    // Declare and assign a local variable
    uint256 c = a + b;  
      
    // Return the value of the local variable
    return c;  
  }
}


Explanation: The add() function returns the sum of two unsigned integers in this example. The function declares a local variable c, assigns it a + b, and returns c.

Output: 

Output Local Variable

 

Example 2

Below is the Solidity program to find the largest value from an array of unsigned integers. The findMax() function returns the largest value from an array of unsigned integers. The method declares and initializes a local variable max to 0. A for loop iterates across the array and updates max if we find a greater integer. Finally, we return max.

Solidity




// Solidity program to find the largest 
// number from an array of unsigned
// integers
pragma solidity ^0.8.0;
  
contract LocalVariableExample {
    
  function findMax(uint256[] memory numbers) public pure returns (uint256) 
  {
      
    // Declare and initialize a local variable
    uint256 max = 0;  
      
    for (uint256 i = 0; i < numbers.length; i++) 
    {
      if (numbers[i] > max) 
      {
        // Update the value of the local variable
        max = numbers[i];  
      }
    }
      
    // Return the value of the local variable
    return max;  
  }
}


Output: 

Output Local Variable

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads