What is the difference between the constant and immutable keywords in Solidity and how do I use them?


Both immutable and constant are keywords that can be used on state variables to restrict modifications to their state. The difference is that constant variables can never be changed after compilation, while immutable variables can be set within the constructor.

From the docs:

State variables can be declared as constant or immutable. In both cases, the variables cannot be modified after the contract has been constructed. For constant variables, the value has to be fixed at compile-time, while for immutable, it can still be assigned at construction time.

An example code snippet is as follows:

pragma solidity >0.6.4 <0.7.0;

contract C {
    uint constant X = 32**22 + 8;
    string constant TEXT = "abc";
    bytes32 constant MY_HASH = keccak256("abc");
    uint immutable decimals;
    uint immutable maxBalance;
    address immutable owner = msg.sender;

    constructor(uint _decimals, address _reference) public {
        decimals = _decimals;
        // Assignments to immutables can even access the environment.
        maxBalance = _reference.balance;

    function isBalanceTooHigh(address _other) public view returns (bool) {
        return _other.balance > maxBalance;

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

  • How about the cost of gas for these 2 types of variable? – Ender Jul 28 at 5:43
  • Found it: constant values can sometimes be cheaper than immutable values. – Ender Jul 28 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.