Govur University Logo
--> --> --> -->
...

In newer Solidity, what special trick does the compiler do by itself to stop numbers from getting too big or too small, without needing extra tools?



In newer Solidity, specifically from version 0.8.0 onwards, the compiler automatically performs checked arithmetic for all integer types by default. This means that during any arithmetic operation, such as addition, subtraction, multiplication, or division, the compiler implicitly adds checks to ensure the result stays within the valid range of the integer type being used. If an operation would lead to an integer overflow (a value becoming too large, exceeding the maximum representable value for its type, like `uint256.max + 1`) or an integer underflow (a value becoming too small, falling below the minimum representable value for its type, like `uint256(0) - 1`), the transaction will immediately revert. Reverting means the entire transaction is stopped, and all state changes are undone, effectively preventing the invalid state from being recorded on the blockchain. This automatic checking is a significant change from older Solidity versions, where such operations would silently wrap around (e.g., `uint256.max + 1` would become `0`), which often led to critical security vulnerabilities and required developers to manually use external safe math libraries like OpenZeppelin's SafeMath. The compiler inserts the necessary checks into the generated bytecode without the developer needing to write any explicit checking code. However, developers can consciously opt out of this default behavior for specific operations by wrapping them in an `unchecked { ... }` block. This `unchecked` block instructs the compiler to skip these safety checks, which can be useful for gas optimization in scenarios where the developer is absolutely certain that overflow or underflow will not occur, or where the wrapping behavior is intentionally desired.