4

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.

3
  • In C++ all zero values will be converted to false and all non-zero values converted to true. Commented Apr 4, 2020 at 20:11
  • 1
    Anything can be a condition. In a boolean context any non-0 value is considered to be true, and 0 is false. So, as long as "~i" is not 0, the for loop continues iterating. If you think about what value i must have so that ~i is 0, you will have your answer. Commented Apr 4, 2020 at 20:12
  • condition is boolean, and the value of ~i is considere as such. Commented Apr 4, 2020 at 20:13

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.