NOT(~) vs NEGATION(!)

Viewed 93222
#include <iostream>

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

 }

The output is -5,-4,-3,-2. Shouldn't it print values till -1?Why is it only till -2. And please explain me the difference between 'not' and 'negation' operators.When ever I write a program they were the source for bugs.

while(i)

I know that the loop condition will be true for positive and negative i's except 0.

while(!i) vs while(~i)

For what values of 'i' the above two loops get executed?

4 Answers

! 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

Related