Variable Scope: State & Local variables

Variable Scope

Storage variables (aka state variables)

  • Stored in the blockchain and their values are persistent and publicly accessible.

  • Declared outside a function.

contract MyContract {    
    uint public balance; // Declares a state variable
}

Local variables

  • Declared within a function

  • Not stored on the blockchain

contract MyContract {    

    function addOne() public {        
        uint256 localNumber = 2;        
    }
}

Local variables are useful for storing temporary values or intermediate results and can be declared in the same way as any other type of variable.

Contract layout

Visibility

State variables only have three possible visibility modifiers:

  1. public (accessed internally as well as via external function calls)

  2. internal (only accessed internally and inheriting contracts)

  3. private (only within the contract it is defined)

When visibility is not specified, state variables have the default value of internal.

Updating State Variables

  • To write or update a state variable you need to send a transaction.

  • On the other hand, you can read state variables for free, as it does not involve a transaction.

Last updated