What is variable scope in Solidity?
Variable scope
In programming, variable scope refers to how variables can be accessed inside a function or a given program.
For instance, a variable could only be accessed within a function, while in other cases, the same variable could be accessed throughout an entire program.
Therefore, variables that are only accessible within a specific function are called local variables, while those that can be accessed throughout the entire program are termed global variables.
The variable scope in any programming language is hence the area where variables can be accessed.
Solidity, just as any other programming, supports the implementation of variable scope in its programs. Solidity supports three types of variables:
- State variables
- Local variables
- Global variables
All these variables have a defined scope where they can be accessed.
State variables
State variables are permanently stored in the contract’s storage. They are defined outside of any function’s scope.
// Solidity program to demonstrate state variablespragma solidity ^0.5.0;// Creating a contractcontract State_variables {// Declaring a state variableuint8 public state_var;// Defining a constructorconstructor() public {state_var = 16;}}
Local variables
Local variables in Solidity are declared inside a function. They are only accessible within the function.
pragma solidity ^0.5.0;contract Local_variables {uint state_var; // State variableconstructor() public {state_var = 10;}function getResult() public view returns(uint){uint local_var1 = 1; // local variableuint local_var2 = 2; // local variableuint result = a + b; // local variablereturn result; // access the local variable}}
Global variables
Global variables in Solidity are some predefined special variables, that can be used in any scope in a Solidity program. Global variables provide information about the transactions and blockchain properties.
Examples of global variables in Solidity
Global variable | Function |
| Returns the current block difficulty |
| Returns the current block gaslimit |
| Returns the sender of the message (current caller) |
| Returns the complete calldata |
| Returns the current block timestamp |
// Solidity program to show global variablespragma solidity ^0.5.0;// Creating a contractcontract Test {// Defining a variableaddress public admin;// Creating a constructor to// use Global variableconstructor() public {admin = msg.sender;}}
In the above code, msg.sender is the global variable in the solidity program.