Constants and immutables help keep some values fixed in your blockchain program. This makes your code safer and easier to understand.
Constants and immutables in 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.
uint constant MAX_SUPPLY = 1000000;address immutable owner;
constructor() {
owner = msg.sender;
}string constant TOKEN_NAME = "MyToken";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.
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; } }
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.
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.