#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?
When
igets to-1, the value of~iis~-1, or0, so thewhileloop stops executing. The!operator works because it does something completely different; it results in1for0values and0for 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-1is all ones in binary when a two’s complement signed integer.~0b…11111111is0.However:
!0is1,!anythingElseis0-1is not0!-1is still0And if you actually want to loop including
i == -1, just usewhile (i)instead ofwhile (~i).