Solidity Local Variables
Last Updated :
06 Apr, 2023
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
pragma solidity ^0.8.0;
contract LocalVariableExample {
function add(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a + b;
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:
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
pragma solidity ^0.8.0;
contract LocalVariableExample {
function findMax(uint256[] memory numbers) public pure returns (uint256)
{
uint256 max = 0;
for (uint256 i = 0; i < numbers.length; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
return max;
}
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...