Variables, Consts & Immutable
Variables
There are 3 types of variables in Solidity:
localDeclared inside a function.
Not stored on the blockchain.
stateDeclared outside a function.
Stored on the blockchain.
globalProvides information about the blockchain.
Example - Variables
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
contract Variables {
// State variables are stored on the blockchain.
string public text = "Hello";
uint public num = 123;
function doSomething() public {
// Local variables are not saved to the blockchain.
uint i = 456;
// Here are some global variables
uint timestamp = block.timestamp; // Current block timestamp
address sender = msg.sender; // address of the caller
}
}Constants
Constants are variables that cannot be modified
Their value is hard coded into the bytecode of the contract
Using constants can save gas cost
Example - Constants
Immutable
Immutable variables are like constants
Values of immutable variables can be set inside the
constructorbut cannot be modified afterwards
Example - Immutable
Last updated