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...
In the code below, all of the following assertions held true for me in .c files compiled with Visual Studio 2013 and Keil µVision 5. Notice (bool)2 == true
.
What do the C and C++ standards say about casting non-zero, non-one integers to bools? Is this behavior specified? Please include citations.
#include <stdbool.h>
#include <assert.h>
void TestBoolCast(void)
{
int i0 = 0, i1 = 1, i2 = 2;
assert((bool)i0 == false);
assert((bool)i1 == true);
assert((bool)i2 == true);
assert(!!i0 == false);
assert(!!i1 == true);
assert(!!i2 == true);
}
Not a duplicate of Can I assume (bool)true == (int)1 for any C++ compiler?:
There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.
int i = 0;
bool bi = !!i;
int j = 1;
bool bj = !!j;
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++.
Source: Stackoverflow.com