Does the C standard explicitly indicate truth valu

2020-02-07 19:16发布

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?

标签: c
7条回答
ら.Afraid
2楼-- · 2020-02-07 20:12

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

... yields 1 if the specified relation is true and 0 if it is false. The result has type int.

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 macros true and false 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:

The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

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:

Relational expressions like i > j and logical expressions connected by && and || are defined to have value 1 if true, and 0 if false.

In the test part of if, while, for, etc, "true" just means "non-zero".

The && operator ... returns 1 if both its operands compare unequal to zero, 0 otherwise.

The || operator ... returns 1 if either its operands compare unequal to zero, and 0 otherwise.

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.

查看更多
登录 后发表回答