Solidity by Example: State Variables
Understanding blockchain storage with this sample code demonstrating state variable declarations, public visibility modifiers, constructor initialization, and view functions for reading contract state without gas costs.
Code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
// State variable to store a number
uint256 public myNumber;
// State variable to store a string
string public message;
// Constructor runs once on deployment
constructor(uint256 _initialNumber) {
myNumber = _initialNumber;
message = "Hello Solidity";
}
// Function to update state
function set(uint256 _num) public {
myNumber = _num;
}
// Function to read state (view means no state change)
function get() public view returns (uint256) {
return myNumber;
}
}Explanation
State variables are permanently stored in contract storage on the blockchain, persisting across all function calls and transactions. Writing to state variables requires a transaction and costs gas because it modifies the blockchain state. Specifically, storing a new variable costs approximately 20,000 gas, while rewriting an existing variable costs about 5,000 gas. Reading state variables externally is free when using view or pure functions.
The public visibility modifier automatically generates a getter function, allowing external contracts and users to read the variable's value without explicitly writing a function. Without this modifier, variables default to internal visibility and can only be accessed within the contract or derived contracts. The Ethereum Virtual Machine stores data in 32-byte storage slots, and understanding this layout is crucial for gas optimization.
The constructor is a special function that executes only once during contract deployment, typically used to initialize state variables with starting values. Functions that only read data should be marked as view to indicate they don't modify state, or pure if they don't even read state. This optimization helps reduce gas costs for local calls and clearly communicates function behavior to users and other developers.
State variables can be declared as constant or immutable to save gas. Constant variables are compiled directly into the bytecode, while immutable variables are set once at deployment and then hardcoded. Both avoid using storage slots entirely, significantly reducing deployment and execution costs.
Code Breakdown
uint256 public myNumber; declares a 256-bit unsigned integer stored permanently on-chain.string public message; stores dynamic text data with automatic getter generation.constructor initializes state variables once during contract deployment.view modifier indicates this function reads but doesn't modify blockchain state.
