In programming, variables are named containers in a program's memory that store data types, such as numbers, text, or boolean values, during program execution. They act as placeholders for changing values, allowing programs to process inputs, perform calculations, and manage state dynamically.
Variables store data, such as letters, numbers, character sequences, or true/false values, that programs need to operate.
Solidity variables hold data types like numbers, true/false values, and even Ethereum addresses.
Defining a variable requires specifying its data type (i.e., uint
for unsigned integers, bool
for booleans, or address
for Ethereum addresses), name, and scope of accessibility within the contract.
For instance, you might declare a variable named userBalance
of type uint
to store a user's account balance in your smart contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract BalanceContract {
uint public userBalance; // Declaring a uint variable to store user balance
}
Declaration is the process of defining a variable by specifying its type and name. In Solidity, variables are either declared state variables (at the contract level) or local variables (within functions).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// State variable declaration: accessible throughout the contract.
uint public counter;
// Local variable declaration: exists only within the function.
function count_user() public {
uint localCounter;
}
Declaring a variable informs the compiler of the variable's type and reserves space in memory.
Initialization assigns a starting value to a declared variable. In Solidity, state variables are initialized at declaration, while local variables are always initialized within functions.
// State variable initialized at declaration.
uint public counter = 0;
function setCounter() public {
// Local variable initialization.
uint localCounter = 5;
// Update the state variable.
counter = localCounter;
}
Initializing variables ensures they have a defined value before use, preventing errors like undefined behavior, incorrect calculations, or contract vulnerabilities.
Variables are categorized by scope, lifetime, and mutability. In Solidity, the primary types include:
State variables: Declared at the contract level, state variables are stored on the blockchain and persist between function calls.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract CountUser {
uint public counter = 0; // State variable storing a counter
address public Owner; // State variable storing contract owner's address
string public greeting = "Hello, Cyfrin!"; // State variable storing a text message
}
Examples of state variables include counter
, text messages stored in greeting
, and contract owner addresses in Owner
.
Local variables: Declared within functions, local variables exist only during the function's execution.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract CounterSum {
uint public counter; // State variable
function increment() public {
uint localCounter = counter; // Local variable storing a temporary count
localCounter += 1;
counter = localCounter; // Updating the state variable
}
function calculateSum(uint a, uint b) public pure returns (uint) {
uint sum = a + b; // Local variable storing intermediate calculation
return sum;
}
}
Examples of local variables include localCounter
, intermediate calculation results stored in sum
, and loop iterators a
and b
.
Constant variables: Constant variables have fixed values after initialization. They must be assigned a value at declaration and cannot be modified later.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract CyToken {
uint public constant MAX_COUNT = 100; // A constant variable
uint public constant TOKEN_SUPPLY = 1_000_000; // Total token supply
uint public constant INTEREST_RATE = 5; // Fixed interest rate in percentage
function getMaxCount() public pure returns (uint) {
return MAX_COUNT;
}
function getTokenSupply() public pure returns (uint) {
return TOKEN_SUPPLY;
}
function getInterestRate() public pure returns (uint) {
return INTEREST_RATE;
}
}
Examples of constant variables include MAX_COUNT
, TOKEN_SUPPLY
, and INTEREST_RATE
.
Immutable variables: Immutable variables, introduced in Solidity 0.6.5, are assigned once during contract construction and remain constant.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Timer {
uint public immutable startTime; // the time when the contract starts
uint public immutable creationTime; // the time when the contract is created
uint public immutable deploymentTimestamp; // the timestamp when the contract is deployed
constructor(uint _startTime, uint _creationTime, uint _deploymentTimestamp) {
startTime = _startTime; // Assigned during contract construction
creationTime = _creationTime; // Assigned during contract construction
deploymentTimestamp = _deploymentTimestamp; // Assigned during contract construction
}
}
Examples of immutable variables include startTime
, creationTime
, and deploymentTimestamp
.
Each variable type serves a specific purpose, from maintaining a persistent state to managing temporary calculations.