#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?
The negation of a given statement p is called not p, that if true, exactly expresses what it would mean to be false. The truth table of the NOT operator is shown below. As we can see, a true statement when negated is true, and a false statement when negated is true.
(logical negation) operator determines whether the operand evaluates to 0 (false) or nonzero (true). The expression yields the value 1 (true) if the operand evaluates to 0, and yields the value 0 (false) if the operand evaluates to a nonzero value.
The logical negation operator ( ! ) reverses the meaning of its operand. The operand must be of arithmetic or pointer type (or an expression that evaluates to arithmetic or pointer type). The operand is implicitly converted to type bool .
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)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With