🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Reading and Writing

Reading and writing are the two basic ways functions work with state variables. A writing function changes a stored value, and a reading step returns the value stored now.

addOne writes to the count

The addOne function writes to count. Each call raises the stored count by one.

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

contract StepCounter {
    uint256 public count;

    function addOne() public {
        count = count + 1;
    }
}

A hand-written reader returns the count

This count is not public, so it grows no free getter. The getCount function reads it by hand.

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

contract HandReadCounter {
    uint256 count;

    function addOne() public {
        count = count + 1;
    }

    function getCount() public returns (uint256) {
        return count;
    }
}

A public variable grows a free getter

This count is public, so Solidity builds the reader for you. Calling count() reads it with no hand-written function.

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

contract FreeReadCounter {
    uint256 public count;

    function addOne() public {
        count = count + 1;
    }
}

Example

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

contract Counter {
    uint256 public count;

    function addOne() public {
        count = count + 1;
    }

    function getCount() public returns (uint256) {
        return count;
    }
}

Key points

  • Writing: a function writes when it changes a state variable.
  • Reading: a read returns the value a state variable holds now.
  • Counter: a small contract that stores one count and raises it step by step.
  • Free getter: every public state variable grows a reading function with the same name.
  • Hand-written reader: a function you write yourself that returns a stored value.
  • Repeated writes: each addOne call raises the count by one more.

In this example, count is public, so it grows the free getter count(). The addOne function writes to count by raising it by one. The getCount function is a hand-written reader that returns the same count. Both reads agree after every write.

Note

a count declared with no public word grows no free getter, so it needs a hand-written reader.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

A contract has uint256 public count and no hand-written reader. Which call reads the count?