Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c++ - NOT(~) vs NEGATION(!)

#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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...