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 = 1and!1 = 0, which is not true when using~.Also, remember that
ifstatements check for whether the value is zero or nonzero. Consequently, even if the value of the boolean was0xFFFFFFFE, it would still evaluate totruein an if statement.Hope this helps