I am writing a smart contract that has to be able to compute the sum of two numbers, modulo another number, where the sum might overflow 2**256-1. I'd write this as (a%c+b)%c, to prevent overflow. I tested (a+b)%c in Remix just to see what happens, and, it works when doing pure calculation that just returns the value. It does not work for writing to a variable, or using the value to as the key in a mapping. Why does it work with return (a+b)%c? What are the steps EVM calculates that with to avoid overflow?

1 Answer 1


The solidity compiler has integer literals expression that are evaluated at compile time with arbitrary length arithmetic, that support intermediate values with precision above the EVM 256 bits. If the final results fits in the correct type it will work.

An example from the linked documentation the intermediate results do not fit an uint256 but the final result is 1 and fits an uint8

uint8 public y = 2**800 + 1 - 2**800;

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.