Differences between constant and immutable variables in solidity
Immutable variables
The immutable variables are unable to mutate or change after creation. There are two ways to assign any arbitrary value to immutable variables:
- At the point of their declaration.
- In the constructor of the contract.
Note: The assigned immutables that are declared are considered as initialized only when the constructor of the contract is executing.
Code example
Let's look at the code below:
const hre = require("hardhat");
async function main() {
await hre.run("compile");
const Contract = await hre.ethers.getContractFactory("test");
const contract = await Contract.deploy();
await contract.deployed();
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});Code explanation
- Line 7: We assign the
immutablevariable at the time of declaration. - Line 8: We declare an
immutablevariable to be assigned inside a constructor. - Line 10: We assign the declared
immutablevariable inside the constructor.
The run.js file is used only for display purposes.
Constant
When using constant variables, the value must be assigned where the variable is declared, and it must be a constant at compile time. The value remains constant throughout the execution of the program thus, any attempt to change the constant value will result in an error.
Note: We can also define
constantvariables at the file level.
Code example
Let's look at the code below:
const hre = require("hardhat");
async function main() {
await hre.run("compile");
const Contract = await hre.ethers.getContractFactory("test");
const contract = await Contract.deploy();
await contract.deployed();
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});Code explanation
- Line 8: We assign a value to the
constantvariable at the time of declaration. - Line 11: We print the value of
constantvariable usingconsole.logInt().
The run.js file is used only for display purposes.
Difference between constant and immutable variable
State variables could be specified as immutable or constant. In solidity, we use constant to permanently fix a variable value so that afterward, it can’t be altered. A constant variable is assigned a value at the time of declaration. On the other hand, immutable is also used for the same purpose but is a little flexible as it can be assigned inside a constructor at the time of its construction.
Note: Both
immutableandconstantvariables can't be changed once declared.
Free Resources