Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the built-in type bool in C++ or the stdbool.h type in C defines TRUE and FALSE as not the size of the machine word?

Tags:

c++

c

I was under the impression that bool types either in C or C++ were typdef'ed integers because it was "easier" to handle at the machine level (size of word and what not). But I just did a sizeof and, to my surprise, they return 1 (byte). Is this right? Well, it is, as per my own short experiment, by why does everything tell me I should be using integers?

Just for the sake of interest, see the Wikipedia article on boolean data types for C.

like image 642
Dervin Thunk Avatar asked Nov 19 '25 18:11

Dervin Thunk


1 Answers

C++11 spec, section 3.9.1 [basic.fundamental], paragraph 6:

Values of type bool are either true or false. [Note: There are no signed, unsigned, short, or long bool types or values. — end note ] Values of type bool participate in integral promotions (4.5).

Section 5.3.3 [expr.sizeof], paragraph 1:

The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. The sizeof operator shall not be applied to an expression that has function or incomplete type, to an enumeration type whose underlying type is not fixed before all its enumerators have been declared, to the parenthesized name of such types, or to an lvalue that designates a bit-field. sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1. The result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined. [Note: in particular, sizeof(bool), sizeof(char16_t), sizeof(char32_t), and sizeof(wchar_t) are implementation-defined. (75) — end note ]

Footnote (75) says:

75) sizeof(bool) is not required to be 1

The presence of the footnote suggests that sizeof(bool) equals 1 on enough implementations that they need to remind people it is not necessarily so.

like image 199
Nemo Avatar answered Nov 22 '25 08:11

Nemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!