Key Differences Between Constant and Immutable Variables in Solidity

Key Differences Between Constant and Immutable Variables in Solidity

Constant and immutable are keywords that can be used on solidity state variables to restrict modification to their state. They share similarities in terms of access restriction but have many differences on how they are used.

1 Constant variables can never be changed after compilation.

Immutable variables can be set within the constructor.

2 Constant variable can not be declared without a value, it must be initialized with a value and it can not be set within a constructor.

Immutable variable can be declared without a value. The value can be set using a constructor function which once done, can not be changed.

3 Constant variables can be declared at file level, but without a visibility modifier.

Immutable variables can only be declared at a state variable.

4 Constant variables can be initialized with both value types and non-value types(dynamic size bytes and string) in solidity.

Immutable variables can not be type of string and bytes. This means immutable variables cannot have a non-value type (e.g string, bytes) but bytes1, bytes2, bytes3,...,bytes32 can work with immutable as type.

NOTE:

It is important to note that the solidity compiler does not reserve a storage slot for these variables (constant and immutable) and every occurrence is replaced by the respective value.