Solidity State Variables
State variables are values declared inside a contract that live in its storage. Storage is the contract's lasting memory on the blockchain, so the values stay in place between calls.
A number in storage
This uint256 state variable lives in the contract's storage. Its public getter reads the value back.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract NumberState {
uint256 public count = 12;
}A true-or-false value in storage
A bool state variable holds either true or false. This one starts as true.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract FlagState {
bool public isOpen = true;
}Text in storage
A string state variable holds a piece of text. The text here is set on the declaration line.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract LabelState {
string public label = "Beginner";
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract PlayerCard {
uint256 public level = 1;
bool public isActive = true;
string public title = "Rookie";
}Key points
- State variable: a variable declared inside a contract, outside any function.
- Storage: the lasting memory where a contract keeps its state variables.
- Type: each state variable names a kind of value, such as a whole number, a true-or-false value, or text.
- uint256: the type for a whole number that is never negative.
- bool: the type for a value that is either true or false.
- string: the type for a piece of text.
In this example, PlayerCard declares three state variables inside one contract. The level variable holds the number 1, isActive holds the value true, and title holds the text Rookie. Each one is public, so each one can be read back through its own getter.
Note
A state variable belongs to the contract itself, not to one call of a function.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
Where do state variables live?