Track 4 · Solidity foundations · lesson 3

Types and state variables

9 min


Track 3 said storage is expensive and memory is cheap. Here is what that means with your hands on it.

Counter.solTweak
Loading editor…
Make count start at 10 instead of 0.
Run the code to see what happens.
Nudge
You are changing where the counter begins, not how it increments.
Show me the approach
State variables can be given a starting value on the line that declares them.
Show me the code
Change `= 0` to `= 10`.
Explain the solution
`uint256 public count = 10;` — this value is written into storage when the contract is deployed, which is why deployment costs gas even before anyone calls a function.

The types you will actually use

Solidity has many types. In practice you will spend most of your time with five:

Use uint256 unless you have a specific reason not to. Smaller types like uint8 sound cheaper but usually are not: the EVM works in 32-byte words, so a uint8 gets padded out anyway and can cost more in extra masking instructions.

The exception is packing several small values into one slot deliberately, which is a real optimisation and a later topic.

Predict

A `uint256` holding 0 is set to 5, then later back to 0. Which write costs the most gas?

Choose one answer

Declaring versus assigning

A state variable declared with a value — uint256 public count = 10; — is written into storage during deployment. That is part of why deploying costs gas before anyone has called a thing.

A variable declared inside a function lives in memory and vanishes when the call ends. It costs almost nothing, and it cannot remember anything.

Check

Which of these survives after the transaction that set it finishes?

Choose one answer

Worth remembering

  • Reach for `uint256` by default — smaller integer types are usually not cheaper.
  • Writing a fresh storage slot costs ~22,100 gas; overwriting a used one ~5,000; clearing one earns a refund.
  • Contract-level variables are storage and persist; variables inside functions are memory and vanish.
  • Initialising a state variable costs gas at deployment time.