Solidity Fundamentals

Constants & Immutable variables

Beginner Level

Constant and Immutable Variables in Solidity

In Solidity, we often deal with variables that should not change once defined. For such cases, Solidity provides constant and immutable keywords. These variables are useful for saving gas, improving code readability, and enforcing fixed values in a smart contract.

1. Constant Variables

  • A constant variable is a variable whose value is fixed at compile-time and cannot be modified later.
  • They must be assigned a value at the time of declaration.
  • Constant variables are usually written in UPPERCASE letters by convention.

Example: Constant Variable


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

contract ConstantExample {
    // Constant variable (value fixed at compile-time)
    uint256 public constant MY_NUMBER = 100;
    string public constant GREETING = "Hello Solidity!";

    function getNumber() public pure returns (uint256) {
        return MY_NUMBER; // always returns 100
    }

    function getGreeting() public pure returns (string memory) {
        return GREETING; // always returns "Hello Solidity!"
    }
}

Here, MY_NUMBER and GREETING are constant values. They cannot be changed after compilation.

2. Immutable Variables

  • An immutable variable is similar to a constant, but its value is assigned only once during contract deployment (in the constructor or inline).
  • After assignment, the value cannot be changed.
  • They are more flexible than constants because they can be set dynamically at deployment time.

Example: Immutable Variable


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

contract ImmutableExample {
    // Immutable variable
    address public immutable OWNER;
    uint256 public immutable DEPLOYED_AT;

    constructor() {
        OWNER = msg.sender;             // set only once at deployment
        DEPLOYED_AT = block.timestamp;  // set to deployment timestamp
    }

    function getOwner() public view returns (address) {
        return OWNER; // returns deployer address
    }

    function getDeployedTime() public view returns (uint256) {
        return DEPLOYED_AT; // returns timestamp of deployment
    }
}

In this example:

  • OWNER stores the contract deployer’s address.
  • DEPLOYED_AT records the block timestamp of when the contract was deployed.

Key Differences Between Constant & Immutable

Feature Constant Immutable
Value assigned At compile-time At deployment-time
Change after set Not possible Not possible
Flexibility Fixed and rigid Can be set dynamically at deployment
Gas optimization Saves gas Saves gas, but slightly less than constants

Continue Learning

Explore more topics in Solidity or browse other tutorials.