State Variable

State variable are the variables defined at the contract level:

  • the data location of state variable is always storage (by default and cannot be changed)

  • the state variables are default to internal visibility if not explicitly stated.

Visibility

The visibility rule of state variable is quite similar to function visibility, but with some differences:

  • State variable does not have external visibility. Because it does not make any senses to deny the contract itself to access its own state variable.

  • public - anyone can access, but read-only access. Compiler will generate a getter function automatically.

contract Alice {
    uint public x;
}
 
contract Bob {
    function f() public view returns (uint) {
        Alice alice = new Alice();
        return alice.x(); // call the generated getter function
    }
}

Getter

The state variable inside a contract can not be modified by external extract directly even it is declared as public. Instead, a getter function is generated by the compiler to provide read-only access.

Primitive Types

For primitive types, the generated getter function is trivial, it has no input parameter and return the value of the state variable.

contract PrimitiveGetter {
    uint public x = 42; // state variable
 
    // the generated getter function
    // function x() public view returns (uint) {
    //     return x;
    // }
}

Note

The generated getter function is internal, which means inside the contract or derived contract, you can not access the state variable using the getter function call.

Array Types

For array types, the generated getter function will have an input parameter to specify the index of the array element to be accessed.

contract ArrayGetter {
    uint[] public arr; // state variable
    // the generated getter function
    // function arr(uint index) public view returns (uint) {
    //    return arr[index];
    // }
}