typestar

unchecked in Solidity

0.8 checks arithmetic; unchecked opts out where safe.

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

// 0.8 checks arithmetic by default; unchecked opts out where
// overflow is impossible and gas is worth saving.
contract RowCounter {
    uint256 public row;
    uint256 public constant ROWS = 64;

    function next() external returns (uint256) {
        uint256 current = row;
        unchecked {
            row = (current + 1) % ROWS;  // bounded: cannot overflow
        }
        return current;
    }

    function remaining() external view returns (uint256) {
        return ROWS - row;
    }
}

How it works

  1. Since 0.8, overflow reverts by default.
  2. unchecked { ... } skips the check where bounds make it safe.
  3. The modulo keeps row inside its 64-row bed.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
484
Tokens
72
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 3 of 3 in Data & gas, step 16 of 28 in Language basics.

← Previous Next →