Is 'bool' a basic datatype in C++?
bool is a fundamental datatype in C++. Converting true
to an integer type will yield 1, and converting false
will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like
enum bool {
false, true
};
So did the Windows API. Starting with C99, we have _Bool
as a basic data type. Including stdbool.h
will typedef #define
that to bool
and provide the constants true
and false
. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.
How to use boolean datatype in C?
If you have a compiler that supports C99 you can
#include <stdbool.h>
Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:
#define bool int
#define true 1
#define false 0
In my opinion, though, you may as well just use int
and use zero to mean false and nonzero to mean true. That's how it's usually done in C.
Is bool a native C type?
bool
exists in the current C - C99, but not in C89/90.
In C99 the native type is actually called _Bool
, while bool
is a standard library macro defined in stdbool.h
(which expectedly resolves to _Bool
). Objects of type _Bool
hold either 0 or 1, while true
and false
are also macros from stdbool.h
.
Note, BTW, that this implies that C preprocessor will interpret #if true
as #if 0
unless stdbool.h
is included. Meanwhile, C++ preprocessor is required to natively recognize true
as a language literal.
Why was the boolean data type not implemented in C
That's not true any more. The built-in boolean type, aka _Bool
is available since C99. If you include stdbool.h
, its alias bool
is also there for you.
_Bool
is a true native type, not an alias of int
. As for its size, the standard only specifies it's large enough to store 0
and 1
. But in practice, most compilers do make its size 1
:
For example, this code snippet on ideone outputs 1
:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool b = true;
printf("size of b: %zu\n", sizeof(b));
return 0;
}
Using boolean values in C
From best to worse:
Option 1 (C99 and newer)
#include <stdbool.h>
Option 2
typedef enum { false, true } bool;
Option 3
typedef int bool;
enum { false, true };
Option 4
typedef int bool;
#define true 1
#define false 0
Explanation
- Option 1 will work only if you use C99 (or newer) and it's the "standard way" to do it. Choose this if possible.
- Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better.
If you are undecided, go with #1!
is bool datatype portable in c++?
bool
is a builtin type since the first C++ standard (C++98), so if you have a compiler that conforms to any C++ standard (and arguably, any compiler from the last 20 years) you should be set.
As for pre-standard C++, looking around it seems that, on PC compilers, it made its appearance around 1996-1997 (Visual C++ 5, Borland C++ 5); indeed, GotW #26 mentions that bool
is "the only builtin datatype to be added to C++ since [Stroutroup's] Annotated C++ Reference Manual" (1990), so it's reasonable to deduce that it was born somewhere between 1990 and 1996. Reading around the web 1993 is thrown around quite often as "birth date" for bool
in C++, but I couldn't find a single reliable reference for it.
Although you can still find obsolete pages (mostly from university courses) that explain how to workaround the absence of bool
in old compilers, nowadays there are no compatibility issues using it, unless you are forced to use really ancient toolchains (I'm looking at you, university courses which recommend Turbo C++ in 2018).
Maybe you got confused with C, where bool
appeared only in C99?
Was
bool
available in pre-standard C++ (like Cfront)?
Looking at the sources of Cfront 3.0.3 (1994, although the original 3.0 was released in 1991), bool
is thrown around quite a bit indeed, especially in standard headers such as basic_string.h
.
As for its definition, there is an insane mix of typedef char bool;
(but inside an #ifdef CFRONT_COMPATIBLE_LUCENT
, so maybe it's just a compatibility definition? And WTF, the copyright date is 1996?), #define bool char
, enum bool { false, true };
, as well as a typedef int bool;
in a promisingly-named std_bool.h header (which however has copyright date 1996 as well!).
Looking at the lexer and the parser I couldn't find mentions of bool
, although the demangler cites it as a fundamental type, so there is some evidence that somebody thought it was (or, was going to be) a builtin.
Still, while its precise definition is a bit of a blur, as said above something named bool
with true
and false
values was indeed available and used in the standard library, so, if you plan to compile your code with Cfront 3.0, bool
is probably going to be the least of your concerns. :-)
Incidentally, this trip down ancient C++ brings some sadness as well: Cfront 3.0 shipped with a C++ regex library, something that we had to wait for C++11 to get back again (and which remained segfault-level broken for quite some more years in libstdc++).
What is the printf format specifier for bool?
There is no format specifier for bool
types. However, since any integral type shorter than int
is promoted to int
when passed down to printf()
's variadic arguments, you can use %d
:
bool x = true;
printf("%d\n", x); // prints 1
But why not:
printf(x ? "true" : "false");
or, better:
printf("%s", x ? "true" : "false");
or, even better:
fputs(x ? "true" : "false", stdout);
instead?
Why are C booleans called _Bool?
_Bool
was not originally in C, but was added in the 1999 C Standard. If it had been called bool
then a large amount of existing code would break because many projects made their own type alias bool
already.
The C89 standard set aside identifiers starting with _
followed by upper-case character as reserved for implementation use. This is why new features added to C always start with such names. _Complex
, _Alignof
and _Static_assert
are other examples.
There is also a header <stdbool.h>
which aliases bool
to _Bool
and defines true
and false
; this header can be included by new projects or by projects that didn't already define bool
.
Why didn't C have a boolean data type prior to C99?
If you spend a little time in the library, you don't have to speculate.
Here are some statements taken from Dennis Ritchie's paper on the evolution of C. The context is that Dennis is building on Ken Thompson's language B, which was implemented on the very tiny PDP-7, a word-addressed machine. Because of growing interest, the group got one of the very first PDP-11s. Dennis writes,
The advent of the PDP-11 exposed several inadequacies of B's semantic model. First, its character-handling mechanisms, inherited with few changes from BCPL, were clumsy: using library procedures to spread packed strings into individual cells and then repack, or to access and replace individual characters, began to feel awkward, even silly, on a byte-oriented machine.
The B and BCPL model implied overhead in dealing with pointers: the language rules, by defining a pointer as an index in an array of words, forced pointers to be represented as word indices. Each pointer reference generated a run-time scale conversion from the pointer to the byte address expected by the hardware.
For all these reasons, it seemed that a typing scheme was necessary to cope with characters and byte addressing, and to prepare for the coming floating-point hardware. Other issues, particularly type safety and interface checking, did not seem as important then as they became later.
(Emphasis mine.)
The paper goes on to describe Dennis's struggles to invent a new pointer semantics, to make arrays work, and to come to terms with this newfangled struct
idea. Notions of type safety and distinguishing Booleans from integers did not seem important until much later :-)
In C how much space does a bool (boolean) take up? Is it 1 bit, 1 byte or something else?
If you are referring to C99 _Bool
try:
printf("%zu\n", sizeof(_Bool)); /* Typically 1. */
Note the standard says:
6.2.5
An object declared as type
_Bool
is large enough to store the values 0
and 1.
The size cannot be smaller than one byte. But it would be legal to be larger than one byte.
Related Topics
Difference Between String.H and Cstring
How to Install C++ Plugin to Eclipse
How to Get Hash Code of a String in C++
What Is "->" After Function Declaration
How to Iterate Over a Constant Vector
How Does C++ Exception Handling Translate to MAChine Code
How to Compile Openssl for X64
Question About a Function Definition (Three Dots in Parameters..)
Qt/Qml:Send Qimage from C++ to Qml and Display the Qimage on Gui
C++ Linker Error with Class Static Constexpr
Opencv: How to Visualize a Depth Image