Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 47 ยท Contract Structure

Constructors, Constants and Immutables

Learn how Solidity constructors set up a contract at deployment, and how constant and immutable variables save gas compared to storage.

Some values in a contract never change after it is created: the owner's address, a token's name, the maximum supply, a fee percentage fixed in the design. Solidity gives you three tools for setting up such values, and choosing the right one affects both clarity and gas. A constructor runs once when the contract is deployed. A constant is fixed in the source code. An immutable is set once during deployment and then can never change.

This lesson explains all three, what happens at deployment, and why constant and immutable are cheaper than ordinary state variables.

Three ways to fix a value

constructor Runs once at deployment.
constant Fixed in the source code.
immutable Set in the constructor, then frozen.

Plain state variables stay in storage and cost the most.

1 / 2

The constructor

A constructor is a special function that runs exactly once, at the moment the contract is created, and never again. It is the place to set the owner, store initial settings and mint an initial supply.

SOLIDITY
contract Shop {
    address public owner;
    string public name;
    uint256 public price;

    constructor(string memory shopName, uint256 startingPrice) {
        owner = msg.sender;      // the account that deploys it
        name = shopName;
        price = startingPrice;
    }
}

Inside the constructor, msg.sender is whoever sends the deployment transaction (or the contract that creates this one with new). The arguments you pass at deployment are ABI-encoded and attached to the end of the creation code, so the constructor can read them. There is no way to call the constructor later, and it does not appear in the finished contract, because the constructor code runs during deployment and is not part of the runtime code that stays on the chain. Nobody can call it again, which is why it is safe to use for one-time setup.

A few more facts:

  • A contract has at most one constructor. If you write none, an empty default one is used.
  • A constructor can be payable, if the deployer should be able to send ether in the deployment transaction.
  • Constructors do not have a visibility keyword in modern Solidity (older versions required one).
  • Constructor arguments can be reference types, such as string memory.
  • For inherited contracts, base constructors run first. Inheritance and Overriding covers the order.

One important caveat: during the constructor, the contract has no code yet at its own address, so address(this).code.length is zero. A contract that is still constructing can therefore pass a check like "is the caller a contract?" and look like a wallet, which is another reason not to rely on that check for security.

constant

A constant is a value known when the code is compiled. It must be assigned where it is declared, with an expression the compiler can compute, and it can never be changed:

SOLIDITY
uint256 public constant MAX_SUPPLY = 1_000_000 * 10 ** 18;
uint256 public constant FEE_PERCENT = 3;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
string public constant SYMBOL = "SHP";

The compiler replaces each use of the name with the value itself, so a constant occupies no storage slot, and reading it costs no storage read. By convention constants are written in UPPER_SNAKE_CASE. Digit separators (1_000_000) and the unit suffixes (1 ether, 1 gwei) make the numbers readable. Some built-in pure functions, such as keccak256 of a literal, are allowed in a constant expression.

immutable

Sometimes the value is not known when you write the code but is known when you deploy: the address of a token contract, the deployer, a deadline computed from block.timestamp. That is the job of immutable:

SOLIDITY
contract Crowdfund {
    address public immutable owner;
    uint256 public immutable deadline;
    IToken public immutable token;

    constructor(IToken token_, uint256 durationInDays) {
        owner = msg.sender;
        token = token_;
        deadline = block.timestamp + durationInDays * 1 days;
    }
}

An immutable can be assigned in the constructor (or at its declaration) and cannot be assigned afterwards. Once the contract is deployed, the value is written directly into the contract's runtime code, just like a constant, and reading it costs almost nothing. The compiler rejects any later assignment. Older compiler versions were also strict about reading an immutable inside the constructor, so when in doubt read the constructor's own argument instead of the variable.

Immutables have a limit: they can only hold value types and not dynamic data such as string or arrays (use a constant if the text is known at compile time, or a state variable if it must be set at deployment). And since the value lives in the code of that deployment, a contract used through a proxy cannot rely on its own immutables for per-proxy settings. Proxies and Upgradeable Contracts explains why initializer functions replace constructors there.

Why this saves gas

Reading a normal state variable means loading from storage, which is one of the most expensive operations: around 2,100 gas for the first (cold) read in a transaction and about 100 gas for later reads of the same slot. Reading a constant or an immutable is like reading a literal in the code, which costs only a few gas. Over thousands of calls, using constant and immutable for everything that does not change is one of the easiest optimizations. You also save the one-time cost of writing the value into a storage slot at deployment.

The rule of thumb: if the value is known at compile time, make it constant; if it is fixed at deployment, make it immutable; otherwise use a state variable. It also documents intent, since a reader knows at a glance that owner can never change.

Stand-ins for deployment

The real compiler and EVM cannot run on this site, so the TryIts here are JavaScript stand-ins. The first models a deploy function: it runs the constructor once, stores ordinary variables in a storage object and freezes immutables.

JS A deploy function with constructor and immutables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in counts reads to show why the gas difference adds up. It uses the typical costs mentioned above (2,100 gas for a cold storage read, 100 gas for a warm one, and 3 gas as a stand-in for reading a value embedded in the code). The exact numbers vary by EVM version, so treat them as an illustration.

JS Why constants and immutables are cheaper to read

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: the constructor runs once and is not part of the runtime code, constant is replaced at compile time, immutable is fixed at deployment, and both avoid storage reads. What is the stand-in: JavaScript objects instead of bytecode, a frozen object in place of values embedded in code, and a simplified cost table. The compiler's own checks for assignment happen at compile time, not at run time as here.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a constructor run?

    The constructor runs during deployment only. It is not part of the runtime code, so it cannot be called afterwards.
  2. 2. Which keyword fits an address that is passed to the constructor and never changes afterwards?

    constant needs a value known at compile time. immutable can be assigned once in the constructor and is then fixed in the code.
  3. 3. Why is reading a constant cheaper than reading a normal state variable?

    A storage read costs hundreds or thousands of gas. A constant is replaced by its value at compile time, so nothing is loaded from storage.
  4. 4. Which type of value can an immutable hold?

    Immutables are written into the code at deployment, so they are limited to value types. Dynamic data needs a constant or a state variable.

Summary

  • A constructor runs once at deployment, sets up initial state, and is not part of the runtime code.
  • constant values are known at compile time and inlined; immutable values are set during deployment and then fixed.
  • Both avoid storage reads and writes, which saves gas on every call.
  • Use constant when known at compile time, immutable when known at deployment, and storage when it must change.
  • Immutables hold value types only and do not suit proxy setups, where initializer functions are used.

Next: Events and Logs.