My question seems simple, but I've been perplexed about it:
bool myBool = TRUE;
if (myBool) printf("1 myBool = true\n");
else printf("1 myBool = false\n");
myBool = !myBool;
if (myBool) printf("2 myBool = true\n");
else printf("2 myBool = false\n");
printf("%d\n", TRUE);
printf("%d\n", FALSE);
All of that outputs:
1 myBool = true;
2 myBool = false;
1
0
I understand why that is outputs. My question is how can a !1
equal false
? Because in C and C++, the if
checks for a nonzero value. And the last time I checked:
TRUE = 0x00000001
FALSE = 0x00000000
therefore:
!TRUE = !0x00000001 = 0xfffffffd != 0
EDIT: I guess this confusion stemmed from my period of learning x86 assembly where a not eax, eax
would perform a bit-wise not on eax
(The equivalent of eax = ~eax
in C).
You are confusing logical NOT and bitwise complement. The !
operator returns 0 if the input is nonzero and 1 otherwise. The ~
operator flips the bits of the input. This means that !0 = 1
and !1 = 0
, which is not true when using ~
.
Also, remember that if
statements check for whether the value is zero or nonzero. Consequently, even if the value of the boolean was 0xFFFFFFFE
, it would still evaluate to true
in an if statement.
Hope this helps
To complement the other answers, the specification states (C99 ยง6.5.3.3/5):
The result of the logical negation operator
!
is0
if the value of its operand compares unequal to0
,1
if the value of its operand compares equal to0
.The result has type
int
.The expression
!E
is equivalent to(0==E)
.
!
is a logical not
operator, so any non-zero input produces a result of 0, and a 0 input produces a result of 1.
The result you're thinking of would be from using a bit-wise not, as in ~true
.
User contributions licensed under CC BY-SA 3.0