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 variables
pragma solidity ^0.5.0;
// Creating a contract
contract State_variables {
// Declaring a state variable
uint8 public state_var;
// Defining a constructor
constructor() 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 variable
constructor() public {
state_var = 10;
}
function getResult() public view returns(uint){
uint local_var1 = 1; // local variable
uint local_var2 = 2; // local variable
uint result = a + b; // local variable
return 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

block.difficulty (uint)

Returns the current block difficulty

block.gaslimit (uint)

Returns the current block gaslimit

msg.sender (address payable)

Returns the sender of the message (current caller)

msg.data (bytes calldata)

Returns the complete calldata

now (uint)

Returns the current block timestamp

// Solidity program to show global variables
pragma solidity ^0.5.0;
// Creating a contract
contract Test {
// Defining a variable
address public admin;
// Creating a constructor to
// use Global variable
constructor() public {
admin = msg.sender;
}
}

In the above code, msg.sender is the global variable in the solidity program.

Free Resources