In this track: Write and read Solidity
advanced · 4 MIN READ

State variables versus local variables

Persistence depends on where a value lives and how it is updated.

LET’S PICTURE IT

A notebook entry survives the meeting; a scratch calculation on a temporary board may not.

SEE IT FOR YOURSELF
Pack small values into Solidity storage slotsStep 1 / 4
Pack small values into Solidity storage slotsFirstuint128 A16 bytesSeconduint128 B16 bytesThirduint256 C32 bytesSimple elementary types only; not a complete compiler layoutSlot 0 · 32 bytesUnused · 16 BA · 16 BHigh-order bytes ← → low-order bytesSlot 0 · fullB · 16 BA · 16 BDeclaration order and sizes determine this packingSlot 0BASlot 1C · 32 bytesTry different sequences in the storage-layout tool

In this simple default-layout example, two uint128 values come before one uint256. Each slot holds thirty-two bytes.

Animated local teaching model. No wallet, RPC or live blockchain data. Some labels and hashes are abbreviated for readability.

State variables belong to storage layout

A declared state variable can persist between calls. Its location and representation follow Solidity’s storage rules, including packing and inheritance context.

Locals support execution

Local variables can hold temporary values or references with specific data locations. A local copy of a number is not automatically a new persistent field.

References deserve extra care

For arrays, structs and other reference types, storage and memory annotations can determine whether code changes persistent data or operates on a copy. Similar-looking assignment syntax can have different effects.

Read the update path

The example computes next locally and then explicitly writes it into count. Without the assignment to the state variable, the computed value alone would not update persistent storage.

Read the example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract LearningExample {
    uint256 public count;

    function increment() external {
        uint256 next = count + 1;
        count = next;
    }
}

next is local; assigning count performs the persistent update.

TURN UNDERSTANDING INTO PRACTICEOpen the Storage layout →
QUICK CHECK · NO PRESSURE

Does calculating a local next value automatically overwrite a state variable named count?

Your progress stays in this browser.
Keep exploring the original referenceSolidity documentation ↗

Original explanations by EtherTools. Examples are educational and source-linked; this site is independent of the Ethereum Foundation. Our approach.