I've found this code in a Solidity contract, and had seen a presentation where this sort of code was used as well. In the work I've done in compilers the intermediate results of expressions are stored in the largest data type available, so this sort of test would fail to reveal overflow; overflow wouldn't happen until the result was stored back into the original variable.

// Making double sure uint doesn't overflow and wrap back
require(totalSupply + _value > totalSupply); 

Is this sort of test valid in Solidity? What are the rules for deciding the type to use for intermediate values in expressions?


In regard to intermediate computation results the Solidity documentation only mentions number literal expressions:

Number literal expressions retain arbitrary precision until they are converted to a non-literal type (i.e. by using them together with a non-literal expression). This means that computations do not overflow and divisions do not truncate in number literal expressions.

Further it talks about Implicit Conversions:

If an operator is applied to different types, the compiler tries to implicitly convert one of the operands to the type of the other (the same is true for assignments)

Since nothing is mentioned about the type of the result in case the operands have the same type, it implies that the compiler will use the same type as the operands.

So the general rule is: for arithmetic operations when operands are of the same type the intermediate result is of the type of the operands; if operands are of different types, the compiler tries to implicitly convert one of the operands to the type of the other and uses this type for the result.

The documentation should have a section explaining issues around arithmetic expressions. There is an issue on Github for this.

To know for sure we would have to dig into the compiler sources. Or you can try this simple test:

function testOverflow() returns(bool) {
    uint8 var1 = 255;
    uint8 var2 = 10;
    return var1 + var1 > 255;

The function returns false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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