Does the C standard explicitly indicate truth value as 0 or 1?

前端 未结 7 1515
日久生厌
日久生厌 2020-12-08 06:14

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         


        
7条回答
  •  失恋的感觉
    2020-12-08 07:10

    It is not explicitly indicated in C11. All language-level operations will return 1 as truthy (and accept any nonzero including NaN as true).

    • If you concern about _Bool, then true must be 1 because the standard only require it to hold 0 and 1. (§6.2.5/2).
    • Also in the macro true expands to 1 (§7.18/3)
    • ==, !=, <, >, <= and >= return 0 or 1 (§6.5.8/6, §6.5.9/3).
    • !, && and || return 0 or 1 (§6.5.3.3/5, §6.5.13/3, §6.5.14/3)
    • defined expands to 0 or 1 (§6.10.1/1)

    But all standard library functions e.g. islower just say "nonzero" for truthy (e.g. §7.4.1/1, §7.17.5.1/3, §7.30.2.1/1, §7.30.2.2.1/4).


    §6.2.5/2: An object declared as type _Bool is large enough to store the values 0 and 1.

    §6.5.5.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. …

    §6.5.8/6: Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.107) …

    §6.5.9/3: The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence.108) Each of the operators yields 1 if the specified relation is true and 0 if it is false. …

    §6.5.13/3: The && operator shall yield 1 if both of its operands compare unequal to 0; …

    §6.5.14/3: The || operator shall yield 1 if either of its operands compare unequal to 0; …

    §6.10.1/1: … it may contain unary operator expressions of the form — defined identifier — or — defined ( identifier ) — which evaluate to 1 if …

    §7.4.1 (Character classification functions)/1: The functions in this subclause return nonzero (true) if and only if …

    §7.18/3: The remaining three macros are suitable for use in #if preprocessing directives. They are — true — which expands to the integer constant 1, …

    §7.17.5.1/3: The atomic_is_lock_free generic function returns nonzero (true) if and only if the object’s operations are lock-free. …

    §7.30.2.1 (Wide character classification functions)/1: The functions in this subclause return nonzero (true) if and only if …

    §7.30.2.2.1/4: The iswctype function returns nonzero (true) if and only if …

提交回复
热议问题