I have
int x = 5;
printf("%d", x); //i get 5... expected
x = !x;
printf("%d", x);// i get 0... hmm
5 in binary is: 0101
if we apply the inverse to each bit, we should get 1010, but !
is not necessarily an inverter, it's a logical operator. Why do i get a 0
?
is the reason that, in C, a positive number is treated as true and so !
-ing it would result in 0?
is this compiler specific?
The not (!
) operator returns either 0
or 1
, depending on whether the input is non-zero or 0
respectively.
If you are looking for a bitwise negation, try ~x
.