James Kanze said:
I know that C99 added _Bool, but I'm not too sure about its
semantics. If I understand the C++ standard correctly, it
guarantees that, given:
bool b ;
int i ;
, i = b will result in i having the value of 0 or 1, and b = i
will result in b having the value false if i == 0, and true
otherwise.
Yes, and this is true in C also. (Lets assume stdbool.h is included
then we can use "bool".)
I'm not sure, but I don't think it makes any
guarantees with regards to what the actual bits in b contain.
In C, because _Bool is an unsigned integer type, it is composed only
of value bits and padding bits and because its value can be only 0 or
1 we know that there is only one value bit. All the other
sizeof(_Bool)*CHAR_BIT bits are padding.
I
think an implementation could ue 43 for true, and 7 for false,
as long as it did the conversions correctly. (Practically,
speaking, of course, no implementation will do this.)
A C implementation could use those values, but I am not entirely sure
a C++ implementation could. C could not, however, use 15 for false
and 7 for true since one of the bits must be a value bit set 1 to
represent 1 and 0 to represent 0. For an 8-bit bool there are two
eligible value bits in your 43/7 example.
And because C and C++ do define bool differently (i.e. using
different words---the definitions in C99 are not copied from
C++), it's far from sure that C offers the same liberty in this
regard. (At the "correct" usage level, they should behave the
same.)
My reading of C++ is that there is slightly /less/ freedom in the
representation used for bool. bool is an integer type in C++ (but it
is not guaranteed to be unsigned as in C) and integral types must use
a "pure binary representation" using 2's complement, 1's complement or
sign and magnitude. I can't see any permission for padding bits
within a POD of integral type. Of course, all the explicit talk of
conversions in C++ may be intended to say that, while there may be
lots of bits in the value of a bool, you never "see" them because it
always converts to 1 or 0 and always compares to true or false.