NOT(~) vs NEGATION(!)

! is true/false logic flipping

! means any nonzero becomes 0, and 0 becomes 1

eg1. !0b1010 -> 0b0000

eg2. !0b0000 -> 0b0001

eg3. !0b1111 -> 0b0000

generalised, out = in?0:1

while...

~ is bit flipping

~ means flip each and every bit

eg1. ~0b1010 -> 0b0101

eg2. ~0b0000 -> 0b1111

eg3. ~0b1111 -> 0b0000

generalised, out = in^0b1111


You are correct about i == -1 being the exit condition: your loop is equivalent to

int i=-5;
while(i != -1)
{
    cout<<i;
    ++i;
}
// i == -1 immediately after the loop

When written this way, it should be clear why -1 is not printed the value is first printed, and only then incremented, that's why -2 is the last value that you print.

The ! operator, on the other hand, will produce 1 only when it is given a zero. That's why the loop would print -1 when the ! operator is used in the loop condition.


'~' is the operator that : ~x = -x-1 and when i = -1, then ~i = 0. if you wonder the value of ~i, you can just print them out:

#include <iostream>

using namespace std;
int main(int argc, char *argv[]) 
{
   int i=-5;
   for (int i = -5; i <= 3; i++)
   {
    cout<<i<<"  "<<(~i)<<endl;
   }
 }

and then you will find: -5 4 -4 3 -3 2 -2 1 -1 0 0 -1 1 -2 2 -3 3 -4


When i gets to -1, the value of ~i is ~-1, or 0, so the while loop stops executing. The ! operator works because it does something completely different; it results in 1 for 0 values and 0 for all other values. ~ is a bitwise negation.

A little more in detail:

  • ~ takes each bit in a number and toggles it. So, for example, 100102 would become 011012
  • -1 is all ones in binary when a two's complement signed integer.
  • ~0b…11111111 is 0.

However:

  • !0 is 1, !anythingElse is 0
  • -1 is not 0
  • !-1 is still 0

And if you actually want to loop including i == -1, just use while (i) instead of while (~i).