DEV Community

Cover image for Immutable State Variables in Solidity
Shlok Kumar
Shlok Kumar

Posted on

Immutable State Variables in Solidity

Immutable state variables are used to define storage identifiers that offer more flexibility as their values can be changed after declaration

State variables can be marked immutable which causes them to be read-only, but assignable in the constructor. The value will be stored directly in the code. Once values are assigned to immutable variables in the constructor, they cannot be modified later on.

The following code will throw an error, since we are trying to modify the value of the variable ‘a’ using a setter function, which is not allowed since ‘a’ is an immutable variable.

pragma solidity ^0.8.0;

contract TestImmutable {
    uint256 public immutable a;
    // This is a valid constructor
    constructor (uint256 _a) public {
        a = _a;
    }
    // This is invalid and will not compile
    function setA (uint256 _a) public {
        a = _a;
    }
}
Enter fullscreen mode Exit fullscreen mode

It is important to know that the code that the compiler uses to create a contract will change the runtime code of the contract before it is returned. It will do this by replacing all references to immutables with the values that have been assigned to them. This is important if you want to compare the code made by the compiler and the code stored in the blockchain.

Immutable state variables in Solidity are variables that cannot be modified after the contract has been constructed. They can be declared using the keyword "immutable" and can be assigned an arbitrary value in the constructor of the contract or at the point of their declaration. Immutables are stored directly in the deployed bytecode, meaning that they are not stored at a fixed offset in storage like regular state variables.

Immutables are different from constant variables, which must have a fixed value at compile time and must be assigned where the variable is declared. Constant variables cannot access storage or blockchain data, while immutable variables can.

Immutables can be used to save on storage costs as they do not require additional storage space for their values. This makes them useful for storing values such as addresses, hashes, and other data that do not need to change over time. Additionally, immutables can help improve code readability by making it easier to identify which values are intended to remain unchanged throughout the lifetime of a contract.

For more content, follow me at - https://linktr.ee/shlokkumar2303

Top comments (0)