Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C/C++ bool type always guaranteed to be 0 or 1 when typecast'ed to int?

Tags:

c++

c

boolean

Many compilers seem to be keeping only 0 or 1 in bool values, but I'm not sure this will always work:

int a = 2; bool b = a; int c = 3 + b; // 4 or 5? 
like image 989
mojuba Avatar asked Nov 25 '10 10:11

mojuba


People also ask

Is bool always 0 or 1?

Boolean values and operations C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.

Is a bool automatically true?

bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?

Is bool a valid type in C?

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

When did bool add C?

An introduction to how to use booleans in C C99, the version of C released in 1999/2000, introduced a boolean type. To use it, however, you need to import a header file, so I'm not sure we can technically call it “native”.


1 Answers

Yes:

In C++ (§4.5/4):

An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

In C, when a value is converted to _Bool, it becomes 0 or 1 (§6.3.1.2/1):

When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

When converting to int, it's pretty straight-forward. int can hold 0 and 1, so there's no change in value (§6.3.1.3).

like image 91
Matthew Flaschen Avatar answered Oct 11 '22 01:10

Matthew Flaschen