Constants Variables
Introduction
Constant variables are variables whose value is known at compile-time and cannot be changed at runtime. In Solidity 0.8.16, constant variables are declared using the constant
or immutable
keyword, and can be used to store values that do not change over the lifetime of a smart contract. In this blog post, we will explain constant variables in Solidity 0.8.16 and provide an example smart contract that uses them.
Constant Variables in Solidity 0.8.16
In Solidity 0.8.16, constant variables are declared using the constant
or immutable
keyword, followed by the variable name, the data type, and the initial value.
Here's an example of a smart contract that uses constant variables:
// SimpleMath.sol
pragma solidity ^0.8.0;
contract SimpleMath {
uint constant public RESULT = 42;
function getAnswer() public pure returns (uint) {
return RESULT;
}
}
In this smart contract, we have defined a constant variable called RESULT
with a data type of uint
. The value of RESULT
is set to 42 at the time of declaration, and cannot be changed at runtime.
We have also defined a getAnswer()
function that returns the value of RESULT
. Since RESULT
is a constant variable, its value is known at compile-time and can be used directly in the function.
Conclusion
In this blog post, we explained constant variables in Solidity 0.8.16 and provided an example smart contract that uses them. By understanding constant variables, you can write smart contracts that store and use values that do not change over the lifetime of the contract. This can be useful for implementing contract-level configurations, such as fixed prices or maximum limits.
Feedback
Have feedback? Found something that needs to be updated, accurate, or explained?
Join our discord and share what can be improved.
Any and all feedback is welcomed.