0

I'm having trouble understanding LowGasSafeMath. For example, how does this function work?

function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
    require(x == 0 || (z = x * y) / x == y);
}

The first thing that puzzled me is that this returns a value without a return statement. Then, how does the logic inside the require statement work? As a programmer, I'm familiar with boolean logic, but haven't seen it used like this before.

2
  • require statement is the equivalent to return from the entire application , or in other words exit so these statements are equivalent to C asserts
    – Nulik
    Jul 11 '21 at 15:32
  • these statements are basically checking for the multiplication to overflow the 256 bit integer value. , the result of multiplication must be larger then the operands, thats what it does
    – Nulik
    Jul 11 '21 at 15:35
0

Return is done with returns (uint256 z). This means that when the function ends the variable z is returned. The function checks if there was an overflow in the multiplication, because then the result would be wrong. To make sure it is correct, the result of z = x* y is decided by x, if this equals y then the calculation is correct (one could also decide by y). To avoid division by 0, it is checked if x ==0. If this is the case, the whole statement is true and therefore not evaluated further. Because multiplication by 0 is 0, no calculation is needed, because z = 0 by default.

It is the same as

if (x==0) {
    return 0;
}
z = x * y;
require(z / x == y);
return z;

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.