0
0
Blockchain / Solidityprogramming~5 mins

State variables in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

State variables store information permanently on the blockchain. They keep data safe and shared for everyone using the program.

When you want to save a user's balance in a cryptocurrency app.
When you need to remember who owns a digital item in a game.
When you want to track votes in a blockchain voting system.
When you want to store contract settings that affect how it works.
Syntax
Blockchain / Solidity
type variableName;

// Example:
uint256 myNumber;

State variables are declared inside a contract but outside any function.

They are stored permanently on the blockchain and cost gas to change.

Examples
This declares a state variable named count that stores a number.
Blockchain / Solidity
contract Example {
    uint256 count;
}
This declares a state variable named name that stores text.
Blockchain / Solidity
contract Example {
    string name;
}
This declares a state variable named isActive that stores true or false.
Blockchain / Solidity
contract Example {
    bool isActive;
}
Sample Program

This contract has a state variable storedNumber that saves a number. The setNumber function changes it, and getNumber returns it.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 storedNumber;

    function setNumber(uint256 _number) public {
        storedNumber = _number;
    }

    function getNumber() public view returns (uint256) {
        return storedNumber;
    }
}
OutputSuccess
Important Notes

Changing state variables costs gas because it updates the blockchain.

Reading state variables (view functions) does not cost gas if called externally.

State variables keep their value between function calls and transactions.

Summary

State variables store data permanently on the blockchain.

They are declared inside contracts but outside functions.

Use them to remember important information for your blockchain app.