8

I've seen a contract that stores -1 as an unsigned integer.

uint256 can = allowed ? uint256(-1) : 0;

Can anyone explain the benefit of this over something like:

uint256 can = allowed ? 1 : 0;

4 Answers 4

6

By 2s-complement, uint256(-1) is equal to the maximum value of uint256.

So it's essentially a shorter way to write 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.

For bool can, your wondering would be correct (i.e., allowed ? true : false would suffice).

But since uint256 can is used, the answer to your question depends on what it is used for...

2
  • OK, that's clarified a lot. Digging further, this variable is used to set the spending allowance. I was looking at it as if it were setting a boolean in some way.
    – Nick
    Feb 25, 2020 at 14:07
  • 1
    @Nick: Yeah, if it was setting a boolean, then most likely no code was needed to begin with, since that boolean is already given as input, right? I mean, what else could allowed be? But you're right about the name can implying of a boolean variable; it's probably just a bad naming-choice. Feb 25, 2020 at 14:15
2

uint256(-1) is a trick to gives the maximum uint256 value.

1
  • Note that it was already mentioned a few minutes ago in the answer above. Feb 25, 2020 at 14:06
1

Use type(uint256).max for better readability. Supports Solidity >= 0.6.8

0

Here is another REAL purpose

Tests are passing:

for (uint256 i = pendingDepositsLength - 1; i != uint256(-1); i--) {

Test are failing:

for (uint256 i = pendingDepositsLength - 1; i >= 0; i--) {

Explanation

i-- causes underflow and i becomes a really large number.

uint256(-1) solves that. Clever use case, not sure about readability.

I wanted to refactor but the failing tests raised the alarm.

Your Answer

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

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