Understanding "not" on booleans

2

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).

c
boolean
c99
boolean-logic
asked on Stack Overflow Jul 11, 2012 by Cole Johnson • edited Apr 3, 2013 by Cole Johnson

3 Answers

10

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

answered on Stack Overflow Jul 11, 2012 by templatetypedef
5

To complement the other answers, the specification states (C99 ยง6.5.3.3/5):

The result of the logical negation operator !is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0.

The result has type int.

The expression !E is equivalent to (0==E).

answered on Stack Overflow Jul 11, 2012 by James McNellis
2

! 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.

answered on Stack Overflow Jul 11, 2012 by Jerry Coffin

User contributions licensed under CC BY-SA 3.0