17 - State Mutability
State Variables: Constant & Immutable
-
State variables can be declared as
constant
orimmutable
. In both cases, the variables cannot be modified after the contract has been constructed. Forconstant
variables, the value has to be fixed at compile-time, while forimmutable
, it can still be assigned at construction time i.e. in the constructor or point of declaration. -
For constant variables, the value has to be a constant at compile time and it has to be assigned where the variable is declared. Any expression that accesses storage, blockchain data (e.g.
block.timestamp
,address(this).balance
orblock.number
) or execution data (msg.value
orgasleft()
) or makes calls to external contracts is disallowed. -
Immutable variables can be assigned an arbitrary value in the constructor of the contract or at the point of their declaration. They cannot be read during construction time and can only be assigned once.
-
The compiler does not reserve a storage slot for these variables, and every occurrence is replaced by the respective value.
- State Mutability: Specifiers
- constant: Fixed at Compile-time
- immutable: Fixed at Construction-time
- No Storage Slot
- Storage/Gas Efficiant