Solidity Unchecked Math
Unchecked math is arithmetic inside an unchecked block that skips the overflow checks Solidity normally applies. It is safe only where overflow cannot happen by construction.
Unchecked addition wraps past the maximum
Adding one to the largest uint8 wraps to zero inside an unchecked block. The same addition reverts in a checked function.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract WrapDemo {
function bumpUnchecked(uint8 x) public pure returns (uint8) {
unchecked {
return x + 1;
}
}
function bumpChecked(uint8 x) public pure returns (uint8) {
return x + 1;
}
}An unchecked loop counter sums correctly
The counter rises inside an unchecked block because the array length bounds it. The sum comes out exactly right.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract LoopCounter {
function sumWithUncheckedCounter(uint256[] calldata xs) external pure returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < xs.length;) {
total += xs[i];
unchecked {
i++;
}
}
return total;
}
}Checked addition reverts past the maximum
Adding one to the largest uint256 reverts under normal checked math. Small additions still work as usual.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CheckedAdd {
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract SafeCounter {
uint256 public total;
function addUpTo(uint256 n) public {
for (uint256 i = 0; i < n;) {
total += 1;
unchecked {
i++;
}
}
}
function addChecked(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
}Key points
- Checked math: Solidity reverts when an addition overflows.
- Unchecked block: an unchecked block skips those overflow checks.
- Wrapping: an unchecked addition past the maximum wraps around to zero.
- Loop counters: a counter bounded by an array length cannot overflow its bound.
- Use unchecked to skip checks only where overflow is impossible by construction.
In this example, a counter adds items with an unchecked loop counter bounded by the requested count. A separate checked addition still reverts when it would overflow.
Note
never use unchecked math on balances or amounts a user can control.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
When is unchecked math safe?