Ignore Safe Math (unchecked) – But Know What You Do!

Published by Mario Oettler on

Last Updated on 24. March 2025 by Mario Oettler

Solidity checks integer underflows and overflows by default. These checks cost gas. By switching of these checks, it is possible to safe some gas.

The following code snipped shows the difference.

pragma solidity 0.8.29;

contract Checks{
    uint256 a = 1;
    uint256 b = 1;
    function uncheckedCalc() public{
        unchecked{
            a = a + 1;
        }
    }

    function checkedCalc() public{
        b = b + 1;
    }
}
Checked/uncheckedGas Costs
Checked (safe)5320
Unchecked (unsafe)5161

Caution: Switching off under or overflow checks can result in vulnerable contracts. So, make sure that these checks are not necessary.

Categories: