2

I know this might sound obvious but in solidity you can never be too sure.

Let us say I have three numbers 5, 7 and 8. Can I add them like so:

using SafeMath for uint256;

5.add(7.add(8));
// or even like so
5.add(7).add(8);
// or
5.add(7 + 8);

Is there any risk(of overflow or anything else) of using either?

1 Answer 1

2

Writing 5.add(7) is a syntax sugar for add(5, 7).

So first expression 5.add(7.add(8)) is add(5, add(7, 8)) and the second one 5.add(7).add(8) is add(add(5, 7), 8).

In the particular case of SafeMath's add both expression will arrive at the same result. For other functions like sub and div make sure they are in the correct order.

The last expression 5.add(7 + 8) isn't like the others, since 7 + 8 is never checked for overflow. Here it doesn't matter because they are small numbers, but if you used variables it might break.

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.