Ethereum-Solidity Quiz Q29: What is an Overflow/Underflow?
Source: Dev.to
Overflow and Underflow
Overflow and underflow are arithmetic errors that occur when a calculation produces a number outside the fixed range of the variable’s data type.
| Term | What happens | Example (uint8: range 0–255) |
|---|---|---|
| Overflow | You exceed the maximum value and the number “wraps” to the bottom. | 255 + 1 --> 0 |
| Underflow | You go below the minimum value and the number “jumps” to the top. | 0 - 1 --> 255 |
Solidity versions before 0.8.0
Before version 0.8.0, Solidity did not check for these errors. Developers had to rely on a library such as SafeMath to prevent overflow and underflow.
Solidity 0.8.0 and later
Starting with Solidity 0.8.0, the compiler includes built‑in checks. If an overflow or underflow occurs, the transaction automatically reverts with a Panic error.
unchecked block
When you are certain a calculation is safe and want to save gas by skipping the check, you can wrap the code in an unchecked block:
// This will NOT revert; it will wrap around to 0
unchecked {
uint8 x = 255;
x++;
}
Type‑casting caution
Even in Solidity 0.8.0+, casting a larger type to a smaller one (e.g., uint256 → uint8) can still cause silent wrapping without a revert. Always verify that the value fits within the target type’s range before casting.
Recommendation: use uint256
Unless you have a specific reason (such as fitting data into a single 32‑byte storage slot), prefer uint256. Its massive range (2^256 - 1) makes overflow practically impossible in typical financial applications.