Casting int to bool in C/C++

前端 未结 3 903
轮回少年
轮回少年 2020-12-03 02:29

I know that in C and C++, when casting bools to ints, (int)true == 1 and (int)false == 0. I\'m wondering about casting in the reverse direction...<

3条回答
  •  盖世英雄少女心
    2020-12-03 03:07

    The following cites the C11 standard (final draft).

    6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

    bool (mapped by stdbool.h to the internal name _Bool for C) itself is an unsigned integer type:

    ... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

    According to 6.2.5p2:

    An object declared as type _Bool is large enough to store the values 0 and 1.

    AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool for C++ and _Bool for C.

    Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool behaves as in C++.

提交回复
热议问题