0
0
Blockchain / Solidityprogramming~5 mins

Constants and immutables in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Constants and immutables help keep some values fixed in your blockchain program. This makes your code safer and easier to understand.

When you have a value that should never change, like a fixed fee or a token name.
When you want to save gas by storing values that won't change after deployment.
When you want to make your code clearer by showing which values are permanent.
When you want to prevent accidental changes to important data.
When you want to improve security by locking certain values.
Syntax
Blockchain / Solidity
constant type NAME = value;
immutable type NAME;

constructor() {
    NAME = value;
}

constant values must be assigned when declared and never change.

immutable values are set once during contract creation (in constructor) and then stay fixed.

Examples
This sets a constant number that never changes.
Blockchain / Solidity
uint constant MAX_SUPPLY = 1000000;
This sets the owner address once when the contract is created.
Blockchain / Solidity
address immutable owner;

constructor() {
    owner = msg.sender;
}
A constant string for the token name.
Blockchain / Solidity
string constant TOKEN_NAME = "MyToken";
Sample Program

This contract shows a constant MAX_USERS set to 100 and an immutable owner set when the contract is created. The functions return these values.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract Example {
    uint constant MAX_USERS = 100;
    address immutable owner;

    constructor() {
        owner = msg.sender;
    }

    function getMaxUsers() public pure returns (uint) {
        return MAX_USERS;
    }

    function getOwner() public view returns (address) {
        return owner;
    }
}
OutputSuccess
Important Notes

Constants save gas because their values are stored directly in the bytecode.

Immutables save gas compared to regular variables because they are stored in a special way.

Trying to change a constant or immutable after setting will cause an error.

Summary

Constants are fixed values set at compile time and never change.

Immutables are set once during contract creation and then stay fixed.

Using constants and immutables makes your blockchain code safer and cheaper.