Please explain this code to me , related to getPriorVotes function :)

hi, anyone can please explain this code to me ?

    uint32 lower = 0;
    uint32 upper = nCheckpoints - 1;
    while (upper > lower) {
        uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
        Checkpoint memory cp = checkpoints[account][center];
        if (cp.fromBlock == blockNumber) {
            return cp.votes;
        } else if (cp.fromBlock < blockNumber) {
            lower = center;
        } else {
            upper = center - 1;
        }
    }
    return checkpoints[account][lower].votes;

Thanks

This is a binary search. There is an explanation of similar code here:

Isn't the comment above wrong?
I understand it as "ceil division", but the division is a floor division isn't it?

It will avoid overflow, because the subtraction upper - (uper-lower)/2 will never underflow, thanks to the floor division, right?

Hi, welcome to the community! :wave:

Yes, the division in Solidity is a floor division, but the comment is right, for example, if upper = 5, lower = 2, then upper - (upper - lower) / 2 => 5 - (5-2)/2 = 5 - 1 = 4, so this is a ceiling value.

Gotcha, so the ceil refers to the entire operation. thanks!

1 Like