# 4.9 — Boolean values

In real-life, it’s common to ask or be asked questions that can be answered with “yes” or “no”. “Is an apple a fruit?” Yes. “Do you like asparagus?” No.

Now consider a similar statement that can be answered with a “true” or “false”: “Apples are a fruit”. It’s clearly true. Or how about, “I like asparagus”. Absolutely false (yuck!).

These kinds of sentences that have only two possible outcomes: yes/true, or no/false are so common, that many programming languages include a special type for dealing with them. That type is called a Boolean type (note: Boolean is properly capitalized in the English language because it’s named after its inventor, George Boole).

Boolean variables

Boolean variables are variables that can have only two possible values: true, and false.

To declare a Boolean variable, we use the keyword bool.

To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.

Just as the unary minus operator (-) can be used to make an integer negative, the logical NOT operator (!) can be used to flip a Boolean value from true to false, or false to true:

Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0. Similarly, when Boolean values are evaluated, they don’t actually evaluate to “true” or “false”. They evaluate to the integers 0 (false) or 1 (true). Because Booleans actually store integers, they are considered an integral type.

Printing Boolean variables

When we print Boolean values with std::cout, std::cout prints 0 for false, and 1 for true:

Outputs:

```1
0
0
1
```

If you want std::cout to print “true” or “false” instead of 0 or 1, you can use std::boolalpha. Here’s an example:

This prints:

```1
0
true
false
```

You can use std::noboolalpha to turn it back off.

Integer to Boolean conversion

You can’t initialize a Boolean with an integer using uniform initialization:

(note: some versions of g++ don’t enforce this properly)

However, in any context where an integer can be converted to a Boolean , the integer 0 is converted to false, and any other integer is converted to true.

This prints:

```true
false
```

Inputting Boolean values

Inputting Boolean values using std::cin sometimes trips new programmers up.

Consider the following program:

```Enter a Boolean value: true
You entered: 0
```

Wait, what?

It turns out that std::cin only accepts two inputs for boolean variables: 0 and 1 (not true or false). Any other inputs will cause std::cin to silently fail. In this case, because we entered true, std::cin silently failed. A failed input will also zero-out the variable, so b also gets assigned value false. Consequently, when std::cout prints a value for b, it prints 0.

To make std::cin accept “false” and “true” as inputs, the std::boolalpha option has to be enabled

However, when std::boolalpha is enabled, “0” and “1” will no longer be treated as booleans.

Boolean return values

Boolean values are often used as the return values for functions that check whether something is true or not. Such functions are typically named starting with the word is (e.g. isEqual) or has (e.g. hasCommonDivisor).

Consider the following example, which is quite similar to the above:

Here’s output from two runs of this program:

```Enter an integer: 5
Enter another integer: 5
5 and 5 are equal? true
```
```Enter an integer: 6
Enter another integer: 4
6 and 4 are equal? false
```

How does this work? First we read in integer values for x and y. Next, the expression “isEqual(x, y)” is evaluated. In the first run, this results in a function call to isEqual(5, 5). Inside that function, 5 == 5 is evaluated, producing the value true. The value true is returned back to the caller to be printed by std::cout. In the second run, the call to isEqual(6, 4) returns the value false.

Boolean values take a little bit of getting used to, but once you get your mind wrapped around them, they’re quite refreshing in their simplicity! Boolean values are also a huge part of the language -- you’ll end up using them more than all the other fundamental types put together!

We’ll continue our exploration of Boolean values in the next lesson.

 4.10 -- Introduction to if statements Index 4.8 -- Floating point numbers

### 582 comments to 4.9 — Boolean values

• Miji Maisuka

First Source Code

#include <iostream>
using namespace std;

bool even (int M);/* Write a function prototype for function even, which takes an int parameter and returns a bool*/

int main()
{
int number1; // current input

for ( int M = 1; M <= 4; M++ )// loop for 4 inputs. You can decide how many loop inputs you want.
{
cout << "Enter an integer: ";//The program will ask you to enter the integer/number
cin >> number1;

if (number1 % 2==0 )// determine if the input is even
{

cout << M << " is an even integer\n\n";
}
else
{
cout << M << " is an odd integer\n\n";
}
} // end for

cout << endl;
return 0;
} // end main

Second Code

#include <iostream>
using namespace std;

bool even (int M);//Write a function prototype for function even, which takes an int parameter and returns a bool

int main()
{
int number1; // current input

for ( int M = 1; M <= 4; M++ )// loop for 4 inputs. You can decide how many loop inputs you want.
{
cout << "Enter an integer: ";//The program will ask you to enter the integer/number
cin >> number1;

if (number1 % 2==0 )// determine if the input is even
{

cout << M << " is an even integer True \n\n";
}
else
{
cout << M << " is an odd integer\n\n";
}
} // end for

cout << endl;
return 0;
} // end main

/* Define function even. Use the modulus operator to determine if an integer
is evenly divisible by two. */

bool even (int M)
{
if (M%2==0)//determine whether even or odd
{
return true;
}
else
{
return false;
}
}  // end bool

• Mysterious Wolf

"However, when std::boolalpha is enable, “0” and “1” will no longer be treated as booleans."
Is enable should probably "is enabled"

• Saeko

Guys? Do I need help with this? And how do I code this?
Evaluate the following Boolean expressions. Assume x, y, z have some numerical values.

a. 4 < 5 || 6 ==6
b. 2 < 4 && (false || 5 <==4)
c. x <=y && !(z !=z) || x > y
d. x < y || z < y && y <= z

• sefasu

std::boolalpha is also usable for std::cin according to cppreference. So, I have used the code block:

and get the output:
true
1

Thus, I think editing the sentence  "It turns out that std::cin only accepts two inputs for Boolean variables: 0 and 1 (not true or false)." could be better. I apologize if I am missing something.

• nascardriver

I've added a paragraph about `std::boolalpha` to the section, thanks for pointing it out!

• Shareware

Isn't

bool b3 {};

uniform initialization?

• J34NP3T3R

QUESTION :

std::cout << std::boolalpha; can be turned off
can setprecision be turned off ?

• Ligetisplit

Hi guys, I'm trying to gain familiarity with these concepts and i'm currently hitting a kind of brick wall, the following code compiles fine but it's tiresome to write out the conditions for if statement (and it doesn't run correctly/has a semantic error that I can't find)

Is there a neater/more convenient way to do this? For instance if I had many, many more possible values for these variables, writing out the if statements could take hours upon hours...

additionally, the memberLevel string value gets evaluated as "p" no matter what i plug into it, even integers.. why would this happen?

• nascardriver

You have a whole bunch of duplicate comparisons. Nest your if-statements so you don't have to compare things more than once. Also write functions to make things easier.

If you don't need exact prices, you can define multipliers for each category

> memberLevel string value gets evaluated as "p"
I can't reproduce this.

• Ed Andre

#include <iostream>

using namespace std;

int main()

{
bool isfishgood=true;

if(isfishgood)
{
cout << "Fish is tasty";

}

else
{
cout << "I hate fish";
}

return 0;
}

You can change the outcome of the program just by setting the value of the boolean variable, if set to true, it will return fish is tasty, otherwise it wil return I hate fish

• Hi, quick question.  You said in earlier chapter that only initialized value to variable if you are going to use it.  Then, why initialized it in this case?

It would make more sense to not initialize it? or C++ initialize it to 0 by default?

exp:
std::cout << "n/a";
int i{};  //in this line, leave it blink? why initialize it to 0?
std::cin >> i;

• nascardriver

Those should be left blank. Thanks for pointing it out!

• James

Hey I was playing with the different examples and noticed that if I enter a value other than 1 or 0 for the boolean b, causing std::cin to "silently fail" and zeroing the variable, later uses of std::cin also seem to fail. In fact when I later try to ask for user inputted integers, the program fails to ask me at all for any numbers and instead just prints to std::cout with a and c also set to 0. Can you tell me why this is and if there is someway to reset std::cin? Or are scenarios like this dealt with through error/exception handling? Thanks.

• nascardriver

When extraction fails, `std::cin` enters a failed state. As long as `std::cin` is in this failed state, it will refuse to do anything. To get out of that failed state call `std::cin.clear()`. Note that if there was any bad input, it will still be there and your next extraction might fail for the same reason as the previous one.
We cover input error handling in more detail later.

• Felix

a little typo here
"It turns out that std::cin only accepts two inputs for Boolean variables: 0 and 1 (not true or false). "
it should be true or false instead of "not true or false"

• nascardriver

It is correct as written, it means that `std::cin` does not accept true or false as input for a boolean.

• Haseeb Ur Rehman

Design a C++ code that has the same behavior as a XOR gate. Input variable must be
of Bool Data type.

• Hi

(a || b) && !(a && b)

It seems to be that a best practice should be to **not** use cin directly for booleans unless there are performance reasons. It seems to me that the best practice should be to use cin to populate a string, and then populate a boolean after that. If this is correct, you may want to add a best practice as such. Possibly to name an alternative best practice as to ask people to put in a "1" or a "0"

• Keshav

Can't this be done without using boolean integrals?
I think it can be done without boolean integrals.

• nascardriver

What do you mean by "boolean integrals"?

• Keshav

i meant boolean values.

• nascardriver

You can do everything without types, but that's not the point. Types are there to help you.

• asparagus boi

BUT I like asparagus :(

• Keshav

well it is good for health.

• Rupi

Inputting Boolean values

Inputting Boolean values using std::cin sometimes trips new programmers up.

Consider the following program:

you forget the #include <iostream>; its a small thing, which might have been forgotten deliberately.

• nascardriver

I added it, thanks! Some old snippets don't have includes. If you find more, feel free to point them out.

• Fosterwerks

What exactly is std::boolalpha? From what I gather it's a function. Assuming it is, why can we use it without parentheses?

• nascardriver

`std::boolalpha` is both a function and a variable of type `std::ios_base::fmtflags`, which is an implementation-defined type, ie. it's unknown to us what this type is, it can vary between standard libraries. In this example, we're using the variable. When a stream, for example `std::cout`, receives a variable of this type, it changes some of its internal settings rather than printing the variable.

• Raffaello

brace initialization shouldn't be allowed on line 5, in fact when I tried it wouldn't compile, complaining about "narrowing conversion of '4' from 'int' to 'bool'". so I changed it to copy initialization, but left the brace initialization on line 8 and it did compile, why is that?

• nascardriver

Brace initialization doesn't allow conversions which can cause loss of data. If you convert 4 to a bool, you lost information, because afterwards you only know if the integer was 0 or not.

• 3li Mot 3alim

why my compiler allows implicit conversion from int to bool using uniform initialization?
(code::blocks 20)

this prints true.

• nascardriver

shouldn't compile. I tried with clang, gcc, and msvc, all of which rejected the code. Which compiler are you using?

• 3li Mot 3alim

GNU GCC compiler.

• nascardriver

gcc falsely accepts

up to version 8. From gcc 9 onward, the code is rejected. Unless you have a good reason to still be using gcc 8, I suggest using a more recent version of gcc (Currently gcc 10 is the most recent release).

• 3li Mot 3alim

Sorry,
How can I check the version of my GCC compiler?

• nascardriver

Run `g++ -v` in your terminal if you're on linux or mac. I don't know how to do this on Windows.

• 3li Mot 3alim

Thank you very much for your time.

• Mike

Hi.In  "printing Boolean variables" section, shouldn't it be \n in the code instead of std::endl ?

• nascardriver

It should, lesson updated. Thanks for pointing it out!

• Mike

You're welcome.

• Al

Asparagus are great, come on! Fried (not deep fried) with salt and olive oil... :p Bacon is great with aspargus, by the way.

• Craig

Haha, funny. I knew someone would comment on this. Yes, Alex, if your only experience is with canned (or even frozen store-bought) asparagus... I hear ya. Fresh grilled asparagus with lots of butter is amazing!

• Alex

If you have to drown it in butter, aren't you just masking its true nature? :)

When you wrote:

"It turns out that std::cin only accepts two inputs for Boolean variables: 0 and 1 (not true or false). Any other inputs will cause std::cin to silently fail. In this case, because we entered true, std::cin silently failed. In C++11 or newer, this also sets b to 0 (which is the same value it had already been initialized with)."

Did you mean that when a user inputs a value other than 0 and 1 for Boolean variables using std::cin, the variable would be unaffected and would retain the value it had been initialized with?

Because I found that this program does not behave accordingly:

When the user inputs "false" or "true", the program always prints "Boolean value: 0", inconsistent with the initial value of the variable b (true).

Edit: My current guess is that I misunderstood you, in which you meant that such input would result in the variable b getting the value of 0 instead of retaining its initial value.

• Alex

In C++11, failed inputs via std::cin operator >> cause the variable to be zero'd.

• Scarlet Johnson

This program on running shows 0.1 with no precision. Explain?

• nascardriver

`std::setprecision` doesn't do anything on its own. It returns an object that can be passed to a stream to modify the stream's precision.

• Scarlet Johnson

Oook! Thanks.