89DEVs

Constants in Solidity

Constants are used in Solidity when it is clear that a variable will never change. When a state variable is defined as constant its value is assigned at compile time and no modification can be made at runtime. It is further not possible to assign data from the blockchain like block or transaction properties to a constant. These values should be declared as immutable variables.

Advantages

What is the advantage of Constants compared to variables? The contract will save gas when a function is called that uses the constant.

Disadvantages

What is the disadvantage of Constants compared to variables? The main disadvantage of using constants is that we cannot use any blockchain data. For example, it is not possible to assign msg.value, block.number or any other global variables to a constant. The reason is, that constants are defined at compile-time and do not allow any modifications at runtime.

declare Constants

A constant is declared by using the constant keyword followed by the identifier. The best practice is to write constant identifiers in upper case: MY_ADDR instead of my_addr. The constant keyword can be added to the declaration of all data types like boolean, integer and address. // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract Constants { address public constant MY_ADDR = 0x0000000000000000000000000000000000000000; string public constant MY_STRING = 'hello'; uint public constant MY_INT = 123; bool public constant MY_BOOL = true; }

Gas Optimization

How much gas can be saved by using constants instead of variables? Let's use the example from above and compare the use of a constant to a variable. We will then see, how much gas was saved. // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract Constants { address public constant MY_ADDRESS = 0x0000000000000000000000000000000000000000; } contract Variables{ address public my_address = 0x0000000000000000000000000000000000000000; } The constant call costs us 21,420 gas and the variable call costs 23,553. So just by replacing a variable with a constant, we saved around 10% gas in this example.

constant vs. immutable

What is the difference between constants and immutable variables? The main difference is that constants are defined at compile-time, while immutable variables are defined at deployment time. It is possible to assign blockchain data to immutable variables but not to constants. // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract Constants { // does not work because constants are defined at compile time address public constant c = address(this); } contract Variables { // works fine because immutable variables are defined at deployment time address public immutable c = address(this); } If we compile the Constants contract, we will receive the following error message. TypeError: Initial value for constant variable has to be compile-time constant.

        

Summary

Click to jump to section