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;
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityBy 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...
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
uint256(-1) is a trick to gives the maximum uint256 value.
Tests are passing:
for (uint256 i = pendingDepositsLength - 1; i != uint256(-1); i--) {
Test are failing:
for (uint256 i = pendingDepositsLength - 1; i >= 0; i--) {
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.