0

I expect this to underflow and become a big number. But calling this method I get a:

MetaMask - RPC Error: execution reverted

function over() public pure returns (uint) {
    uint a = 0;
    return a - 20;
}

Why is this?

1 Answer 1

4

That's because since solidity 0.8.0 the overflow / underflow are automatically checked :

"Arithmetic operations revert on underflow and overflow. You can use unchecked { ... } to use the previous wrapping behaviour. Checks for overflow are very common, so we made them the default to increase readability of code, even if it comes at a slight increase of gas costs. "

So, a - 20 does cause an underflow that is detected and triggers a revert.

As per the documentation, this would not revert and allow you to observe the huge value returned : 115792089237316195423570985008687907853269984665640564039457584007913129639916

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

contract Test {
  function under() public pure returns (uint) {
        uint a = 0;
        unchecked {
            return a - 20;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.