Solidity Variables – Difference Between Local Variable and State Variable

contract-developmentlocal-variablessoliditystate-variable

I am new to solidity. When I read the solidity documentation, it says local variable and state variable. But I can't find the definition of the two terms.

Can anyone explain the meaning of local variable and state variable, and the difference between them.

Best Answer

State Variables

From the solidity docs here,

State variables are values which are permanently stored in contract storage.

and can be declared in a contract as follow,

contract SimpleStorage {
    uint storedData; // State variable
    // ...
}

Local variables

Carries the usual meaning, that their context is within a function and cannot be accessed outside. Usually these are the variables that we create temporarily to hold values in calculating or processing something. Local variables (of struct, array or mapping) reference storage as pointed out here, local variable will act as an alias for pre-existing one in the storage. Check the example quoted below to understand what happens.

A common mistake is to declare a local variable and assume that it will be created in memory, although it will be created in storage:

/// THIS CONTRACT CONTAINS AN ERROR



 pragma solidity ^0.4.0;

    contract C {
        uint someVariable;
        uint[] data;

        function f() {
            uint[] x;
            x.push(2);
            data = x;
        }
    }

The type of the local variable x is uint[] storage, but since storage is not dynamically allocated, it has to be assigned from a state variable before it can be used. So no space in storage will be allocated for x, but instead it functions only as an alias for a pre-existing variable in storage.

What will happen is that the compiler interprets x as a storage pointer and will make it point to the storage slot 0 by default. This has the effect that someVariable (which resides at storage slot 0) is modified by x.push(2).

The correct way to do this is the following:

pragma solidity ^0.4.0;

    contract C {
        uint someVariable;
        uint[] data;

        function f() {
            uint[] x = data;
            x.push(2);
        }
    }

Defaults for the storage location

Here are defaults for the storage location depending on which type of variable it concerns (source):

  • state variables are always in storage

  • function arguments are in memory by default

  • local variables of struct, array or mapping type reference storage by default

  • local variables of value type (i.e. neither array, nor struct nor mapping) are stored in the stack

Related Topic