Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 'bool' a basic datatype in C++?

Tags:

c++

I got this doubt while writing some code. Is 'bool' a basic datatype defined in the C++ standard or is it some sort of extension provided by the compiler ? I got this doubt because Win32 has 'BOOL' which is nothing but a typedef of long. Also what happens if I do something like this:

int i = true; 

Is it "always" guaranteed that variable i will have value 1 or is it again depends on the compiler I am using ? Further for some Win32 APIs which accept BOOL as the parameter what happens if I pass bool variable?

like image 632
Naveen Avatar asked Dec 10 '08 16:12

Naveen


People also ask

Is bool a standard C type?

an appropriate answer to this is, yes a C standard such as C90, specifically the C99 standard, does implement a bool type.

What data type is bool in C?

In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value.

Is there bool in C?

In C there is no predefined datatype as bool. We can create bool using enum. One enum will be created as bool, then put the false, and true as the element of the enum. The false will be at the first position, so it will hold 0, and true will be at second position, so it will get value 1.


2 Answers

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.

like image 198
Johannes Schaub - litb Avatar answered Sep 21 '22 03:09

Johannes Schaub - litb


Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

like image 40
jalf Avatar answered Sep 24 '22 03:09

jalf