What Does the Bitwise Complement Function Do in a For Loop in C++?

Viewed 143

Take this line of code for example: for(int i=n-1; ~i; --i) My question is what does the ~i mean. What I already know is the for loops needs the following:

for (type var = ; condition; something to do with var) {
code here
}

But how is ~i a condition? All I know is ~i returns the bitwise complement of i, or flip the bits.

2 Answers

In the 2-compliment representation of integers this loop

for(int i=n-1; ~i; --i)

is equivalent to

for(int i=n-1; i != -1; --i)

In c++, this loop

for (int i=n-1; ~i; --i)

will terminate when all the bits of the underlying representation of i are 1s.

In c++-20 the underlying representation of an int is required to be two's complement. The only int with all bits set to 1 in this representation, is -1. So the loop effectively becomes

for (int i=n-1; i != -1; --i)

as @Vlad pointed out in their answer.

Note that implementations pretty much always use two's complement representation, but c++ did not require it before c++20.

Related