We know that any numbers that are not equal to 0
are viewed as true
in C, so we can write:
int a = 16;
while (a--)
printf("%d\n", a); // prints numbers from 15 to 0
However, I was wondering whether true / false are defined as 1
/0
in C, so I tried the code below:
printf("True = %d, False = %d\n", (0 == 0), (0 != 0)); // prints: True = 1, False = 0
Does C standard explicitly indicate the truth values of true and false as 1
and 0
respectively?
There are two areas of the standard you need to be aware with when dealing with Boolean values (by which I mean true/false values rather than the specific C
bool/_Bool
type) in C.The first has to do with the result of expressions and can be found in various portions of
C11 6.5 Expressions
(relational and equality operators, for example) . The bottom line is that, whenever a Boolean value is generated by an expression, it ...So, yes, the result of any Boolean-generating expression will be one for true, or zero for false. This matches what you will find in
stdbool.h
where the standard macrostrue
andfalse
are defined the same way.Keep in mind however that, following the robustness principle of "be conservative in what you send, liberal in what you accept", the interpretation of integers in the Boolean context is somewhat more relaxed.
Again, from various parts of
6.5
, you'll see language like:From that (and other parts), it's obvious that zero is considered false and any other value is true.
As an aside, the language specifying what value are used for Boolean generation and interpretation also appear back in C99 and C89 so they've been around for quite some time. Even K&R (ANSI-C second edition and the first edition) specified that, with text segments such as:
The macros in
stdbool.h
appear back in C99 as well, but not in C89 or K&R since that header file did not exist at that point.