How to create constant variables in Solidity

In this tutorial, we are going to learn how to create constant and immutable variables in Solidity and we're going to see what's the difference

In this tutorial, we are going to learn how to create constant and immutable variables in Solidity and we're going to see what's the difference.

What's the difference between immutable and constant variables?

It sounds like it's the same but there is a slight difference.

Both immutable and constant variables in Solidity are variables that cannot change once you assign a value to it. The difference is that a constant variable has its value hardcoded when you declare it whereas immutable variables can have their value assigned in the constructor only.

How to create a constant variable

Like explained above, a constant variable is a variable that is hardcoded in the smart contract and that you cannot change the value.

To create them, we use the constant keyword and the convention is to use capital letters for their name:

address public constant CONTRACT_OWNER = 0x9F8664D057aaf67ED8a96af49F1d715A96b2b42B;

uint256 public constant EXAMPLE_NUMBER = 123;

How to create immutable variables

Immutable variables are variables you can only define the value in the constructor and that cannot be updated afterwards.

To create them, we use the immutable keyword and the convention is to use capital letters for their name:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Example {
    address public immutable CONTRACT_OWNER;
    unit256 public immutable EXAMPLE_NUMBER;

    constructor(uint256 _number) {
        CONTRACT_OWNER = msg.sender;
        EXAMPLE_NUMBER = _number;
    }
}

And that's it 🎉

Thank you for reading this article, if you want to get better at blockchain development, leave your email below and you'll get:

  • access to the private Discord of a community of Web3 builders
  • access to free guides that will teach you Blockchain Development