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. In C++11 or newer, this also sets b to 0 (which is the same value it had already been initialized with). Consequently, when std::cout printed a value for b, it printed 0.

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

524 comments to 4.9 — Boolean values

• Avneet

Okay...I am confused. I don't know whether it is a good question or not. A boolean variable reserves 1 byte in memory but can only hold two possible values, true(1) or false(0). A single binary digit can also hold two values 1 or 0. My question is why a boolean variables takes 8 bit to represent.

• Alex

It's a good question.

Booleans really only need one bit to represent a true or false state, however as you note, bool variables use a whole byte. Why? Because the smallest unit of memory that a computer architecture can get or set is 1 byte. If booleans were only 1 bit, all of the booleans within the same byte would have the same memory address, and there's be no way to differentiate them!

There are ways to pack 8 booleans into a single byte. I cover these some of these techniques in future lessons.

• Zero Cool

Those techniques you mention are the use of bitmasks right?

• Alex

Bit flags (which are related to bit masks, but slightly simpler).

• Zero Cool

I will get to that topic soon :)

Thanks. (and sorry in advance for my awful english)

• Tree Stan

Hi, I recently attempted the quiz of this section and wanted to avoid writing 4 else if statements. I'm not sure where I went wrong:

• Alex

C++ doesn't parse this expression in the way you're intending.

You could use the logical OR operator to do something similar, like this:

• Tree Stan

Oh, thank you very much.

• Daniel

Hi, I have just completed the quiz, and the program works but it differs from the solution you provided. I'm just wondering if there is something I should do differently:

• Alex

Nope, this is great. It's a better solution than mine because you use logical OR (which we haven't covered yet).

• Andrzej Gertrudziak

Hey Alex.
Is this code correct or the quiz solution is the better way to get around it?

• Alex

You're on the right track, but your program doesn't produce the correct results.

• Andrzej Gertrudziak

Hmmmm,
I am kind of new in to programming so please excuse me any strange sound questions.
So the program as far I understand is taking the value from the user and if it's not 1,4,6 then true value is returned to the function caller which executed the first statement???
Thanks for any inside on this.
I am really enjoying this tutorial so Thanks again.

• Alex

Yes, but:
1) You don't handle 8 or 9 properly.
2) It's odd to define the not-prime numbers instead of the prime numbers.

• shakey2

I came up with a different solution to the one you listed:

Aside from having less to type is there a reason your solution is better than this?

• Alex

Your solution works but has a lot of redundancy. If you ever wanted to update the string "The digit is prime" you'd have to update it in 4 different places.

For a simple program like this that's not that big of a deal, but as programs get more complex, the more you can reduce redundancy the better.

• Vishal

Hello Alex,

First of all, thanks for designing such a great tutorial! It makes learning a lot of fun since the approach is very systematic; not to mention the fact that it uses language that new programmers are comfortable with.

I have a doubt regarding the following program (one of the examples in this lesson)-

Why is it 'if (equal)' ?
Why not 'if (equal == 1)' or 'if (equal == true)' ?
I checked all three variations and they all work perfectly, so what's the difference?

Besides, couldn't we just write the program as-

It makes it shorter, and perhaps there's a lower chance of errors.

Please enlighten me! :P
Thanks!

• Alex

As you note, we use "if (equal)" because it evaluates identically to "if (equal == true)". You can see why this is true by making a table:

equal equal == true
true true
false false

Therefore the "== true" part is redundant.

• Brian

Hi,
I'm using Visual studio 2010.I believe my code is similar to the solution above(in the quiz)However,my program seems to recognize all inputs from user as being prime including numbers that are not prime. How do I solve this?

• Alex

Reply to this message and post your code so we can see what's wrong.

• Brian

• shakey2

line 12:

should be

You want Prime to default to being false because you are only making it true if it matches one of the conditional statements(if (x == 2) for example). If it doesn't match one of those statements then those statements get ignored and Prime stays false so when the program gets to

then it will skip to the else statement(telling the user their number is not prime) because its not true.

• Rohde Fischer

Suggestion for this part, another common prefix for bool functions is has. And since you do a lot to ensure good coding style (love that you do that btw.) I would add that it's not only common but in most cases considered good style, since it for most boolean purposes makes the purpose of the function clearer.

• Alex

Good call. I updated the lesson to note this.

• programmer, another one

in the above solution, couldn't you have put the

if (prime)
cout << "The digit is prime" << endl;
else
cout << "The digit is not prime" << endl;

part inside the other if statements like you would do in most other languages?

for example:

if (x == 2)
prime = true;
std<<cout::"the digit is true";
else if (x == 3)
prime = true;
std<<cout::"the digit is true";
else if (x == 5)
prime = true;
std<<cout::"the digit is true";
else if (x == 7)
prime = true;
std<<cout::"the digit is true";

I've also noticed that c++ does not automatically edit the indentation in the statements like compilers in most other languages would.

Thanks for the reply, and for building this amazing website

• Alex

You could, but I wouldn't recommend doing it this way. Why? Because if you want to change what is printed, you have to change 4 statements instead of one. Although it's not that bad to do with 4 statements, imagine if there were 100, or 1000.

One of the goals when programming should be to reduce redundancy, and your code adds redundancy.

• Rich S.

I'm not sure if I understand the significance between = and ==. I get that = is assigning a value while == is comparing, but it seems like replacing the == with = in the sample code should either give a syntax error or the correct result. When I try this, it compiles correctly, but entering an 8 gives me the result "This digit is prime." I would appreciate it if someone could help me to understand why this is so.

• Alex

It sounds like you're doing something like this:

So first, this will assign the value 2 to x, which probably isn't what you want.

But the real question here is what does x = 2 evaluate to? The answer, it turns out, is x.

So after x = 2 evaluates, you're left with:

which will be true if x is anything other than 0. So the ... part of the code is executing when you aren't expecting it to, and this is setting the value of isPrime to true.

• cpplx

seems like some people have a doubt about operators represented by using common symbols.
maybe if you extend "1.5 — A first look at operators" with that = and == (for example) should be interpreted as "assign" and "compare" NOT as "equals" and "equals equals".
also that == or <= should be interpreted as a single symbol, not 2 keys pressed one after the other, but as if it is 1 key pressed.
make a remark that due the lack of symbols available in the keyboards, the language uses a combination of what is available to represent... stuff.
some educators like to present programmers as being lazy(which might be true for the majority of them) hence the reason to write "==" instead of "compare".
you get the idea. use better words :)

• Snowman

I think I took the quiz too seriously =P

PS. No, I didn't read the hint, it's cheating =D

• Melissa Arredondo

Hi I have an assignment at school similar to this but I'm having a hard time with it. Hopefully someone can help! So the input can be from 2-100 and then determine whether it is prime or not. Then if it is not prime, I need to be able to print whether it is divisible by 2, 3, 5, or 7. How do I do that?

• Tito

I just wanted to share my quiz answer for any future readers.

• Matthew

Thank you for this!  I was trying to figure out how to use bool prime(false) or bool prime(int x) as a forward declaration and could not figure out what I was doing wrong.  Now my compiler errors make sense.

• Daniel Ricci

One additional note: when converting integers to booleans, the integer zero resolves to boolean false, whereas non-zero integers all resolve to true.

At this point, you should just specify that any numerical value that is not 0 or 0.0 w.r.t its data type will be true.

• Carol

Can any one help check my code? There's some semantic error, but I can't figure out why.

#include <iostream>
using namespace std;

bool isPrime(int)
{
int x;
if (x==2)
return true;
else if (x==3)
return true;
else if (x==5)
return true;
else if (x==7)
return true;
else
return false;
}

int main()
{
cout << "Please enter a 1-digit number." << endl;
int myNumber;
cin >> myNumber;

if (isPrime(myNumber))
cout << "The digit is prime" << endl;
else
cout << "The digit is not prime" << endl;

return 0;
}

• Alex

Change:

to:

As you wrote it, you didn't give your function parameter a name, so the value being passed in (myNumber) is being discarded. You defined variable x inside the function, but you never initialized it with a value, so it's essentially useless.

• John

Hi!

So I'm getting the coding right when trying some things, I'm just struggling to understand something. Line 27 of your example to be exact.

On line 26 we declare the variable beEqual. Then we have a function call to IsEqual in order to initialize beEqual. Am I right in assuming that IsEqual will return to the caller function a 1 if both values are equal, and a 0 if they are not equal?

Now line 27. We say: if (beEqual)... what exactly does this mean? Because I'm sure beEqual=beEqual, so why dont we always print "x is equal to y" ?

Or should I read it as: if (1) and if (0)?

I hope I'm making sense here!

• Alex

isEqual() will return true (1) if the values are equal, and 0 otherwise.

"if (beEqual) ..." is the same as writing "if (beEqual==true) ...". So in this case, we're testing beEqual to see if it's true, and which statement is executed depends on whether that equality test is true or false. I'll make this more clear in the lesson text.

• xero

I want to ask why following code works?

#include
int main()
{
using namespace std;
int x;
cout << "Please feed in the first number" <> x;
int y;
cout << "Please feed in the second number" <> y;
bool z;
if (x==y)
z = true;
else
z = false;
if (z)
cout << "Both digits are equal" << endl;
else
cout << "Both digits are different" << endl;
return 0;
}

When the user feeds in two different numbers then the statement which says
if (z)
must hold 0 as z and in return should type "Both digits are equal" because this cout statement follows if (z) statement.

• Alex

is equivalent to:

which means

is equivalent to:

• gurbux

hey nice explanation alex very helpfull...........

• joha

wouldnt it be the same to put instead of x==y, this: x=y????
i tried and got the same result so.....what is the difference and when do I use each operator????

Thanks..

• zingmars

= - assignment operator, used to assign a specific value to whatever you want to assign to.
== - comparing operator, using to compare 2 things.

• Guntis

Yay, I think I completely understand how bool works now.
Thanks Alex, this is so much better than even some of those books on cpp.

P.S. Here's my little test that succeeded btw.

• Abhishek

Hi there, I was just wondering if you just wanted to find if the numbers are equal why have you included the code from line 20 to line 32.

• Mac

Hi, i tried to make this program work with three numbers:

i.e.
return (x == y == z)

the program compiled fine and ran, but did only gave the result for "else" (false)

after i took away "int z" it worked just fine...

does bool only work for two variables?

• yes23

The reason is when you say a == b == c, first it checks a and b and if those two numbers are equal, you are trying to check if c is equal to 1(true). Try this:

bool IsEqual(int a, int b, int c)
{
if(a == b)
{
if(b == c)
return true;
}
else
return false;
}

• Stephan

Great site.
Just wanted to say that I find your site extremely educational, and for me, easy to follow. Good work!

P.S.
I get just as much fun/learning reading the comments at the end of the tutorial as I do from the lessons. I can't finish a section without reading the comments!

Brilliant!!!

• Alex

Could someone please give me a definitive answer about the difference between explicit and implicit assignments.

Thanks

• Daniel

I've never seen that type of assignment used for a built-in, although I do not doubt that it works. I believe that "int i = 1;" uses int's default constructor THEN uses int's assignment operator. Whereas "int j(1);" uses a version of int's constructor which accepts an integer. In theory the second should be more efficient although compilers are most likely smart enough to optimise away the extra step.

• Sam

I don't get how it can run the function bool IsEqual(int x, int y), if there is no function call in the program later. I would figure you would need,

bool Isequal(x,y); <----in main function to call the IsEqual function?

for the program to read

bool IsEqual(int x, int y)
07.{
08. return (x == y); // use equality operator to test if equal
09.}

so how does it work without a function call being made?

• Collin

the if statement calls the function to check if (x==y)

• joel

Great Tutorials, well written and structured. many thanks.

coming from a background in Oracle and using mainly PL/SQL i have gotten used to the idea that booleans are tristate (true, false or null/unknown) and so an if statement against an uninitialsed boolean var would always return null (and thereby only be handled by "else") without any warnings - dangerous.

It might be worth noting for people like me that uninitialised boolean variables, aside from raising a warning at compile and a "break" at runtime (in VC2008 at least), will almost always return true (i assume this because the uninitialised memory address will almost always contain a non-zero value as below).

• someone

Please i need some help...
Can please anyone review this code? It is supossed to accept the input of 2 numbers, the asks for the answer if they are equal and not equal and says if the answer is either right or not:

Thanks!

• yes23

It seems you wrote IsFalse instead of IsEqual.

• Noha

Hey!
In which cases do we use the implicit assignment?

• Alex

You can use it in any case where you're creating a variable and initializing it with a value. It's neither better nor worse than explicit assignment as far as I know.

• Spock

Hey Alex,

Nice tutorial section! Some comments that might improve readability of this section:

1. Mention that the test x==y will output a 0 if false and a 1 if true and discuss the use of this equality as a logic 'test'. It took me a few moments to appreciate that for myself.

2. Logic commands have not been discussed in the tutorial yet (if, not etc) so someone new to programming might find this confusing.

You could also mention that if(1) runs the first command in an if statement and if(0) runs the 'else' statement. Interestingly if(5), if(11) and all if(!=0) has the same effect as if(1). i.e all non-zero values are true in the context of the if statement.

:)

• Alex

Thanks for your thoughts. I added a comment about conversion of integers to booleans because that's not very intuitive to new programmers. Your other comments are valid, but are discussed in future chapters when I tackle those specific topics.

• Kiran

Please correct me if I am wrong:
If the Value of TRUE is 1 (00000001), Doesn't (!TRUE) make the value to be equal to (111111110) internally? If that is the case then evaluating:
if (!TRUE) will always be TRUE.

• Ashish Gupta

Hi,

Actually what u r doing is not correct. u r performing bit wise not that is ~ operator in c.
now u r using operator ! which actually ORs all the bits of the value and then compliments it i.e.
if TRUE is 1(00000001) then ORing will give its value 1(binary not 00000001) this is only a bit so now it will compliment it to 0 and then return the resulting false(000000000).

For futher query you can ask me..on new_programers@yahoo.com
Thnks,

• Alex

Correct. ! is a logical not, whereas ~ is a bitwise not.

• another_programmer

Yup, I had trouble with this one quite a while ago, one thing you'd have to remember is that bool is based on being simply on or off, where if something exists, it's on, and if it doesn't it's off. 1 or 0.

Boolean values are more ideally used if preexisting values exist much like radio buttons, in HTML for example...

<form>
Is your car new or not?<br>
<input name="newCar" type="radio" value="1" /> Yes<br>
<input name="newCar" type="radio" value="0" /> No<br>
</form>

• programmer

I have problem actually I don't know how to use the boolean with ( cin ) ..

like this example:

if i want to ask some one about his car ?

===========
bool car;

=====
is the above good solution or not ??

...

thank you so much

• Alex

When trying to cin boolean values, if the user enters the number 0, this will be treated as the value false. If the user enters anything else, it will be treated as the value true.

There are several ways to proceed:
* Tell the user to enter 0 for no and 1 for yes and then cin a bool.
* Tell the user to enter 'y' or 'n' and then cin a character.

Once you get to the lesson on strings, you could also do this:
* Tell the user to enter "yes" or "no" and then cin a string.

• Shanz

Hi Alex,

I was trying to make the same type of program.  Basically a yes or no question. I'm able to cin a bool easily by having the person enter a 1 for yes, 0 for no.  However  I'm trying to have them input 'y' and 'n'.   You said earlier:

"* Tell the user to enter ‘y’ or ‘n’ and then cin a character. "

I'm confused on how this program is supposed to look.
I've tried many ways, and none work.  This is the last part I've tried to make to get the correct answer.  Can you bool a char?  Could you tell me what I'm doing wrong?

Its ugly but I'm trying haha. I've tried using bool equal(n) and other styles but none work.

• Devashish

These portions of your code are wrong (First of all, if the user is sleeping, he/she isn't going to enter 'y' :) :
You can't define a name twice in the same scope. Giving them different data types won't help. Consequently, defining char ch and bool ch inside same function is not valid. remove the line

from your code. In the same line, you are also assigning a char to a bool. Programmers never do that.

here you are assigning a boolean true to a char. Boolean true evaluates to integer 1 and chars in C++ are treated as integers. If you assign an integer to a char, then the given integer will be treated as an ASCII code and program will print the equivalent character by looking at ASCII table. Integer 1 is equivalent to somewhat called "start of heading" in ASCII table, and is considered unprintable. So, the syntax may be valid, but has no meaning at all. Remove this too.

, Due to the previous changes in your code, this won't work. In fact, you don't even need to define a char n variable. Secondly, this will not do what's supposed. Pretend, because chars are treated as integers, and boolean true or false means integer 1 or 0 respectively, this line of code is a valid if expression. But what would be evaluated? I am not sure but I think true always.

I think you need to go back and read about chars, if-else, data types, ASCII table etc. Your code is a superb mess. After reading those articles again, you may fix all of the errors (all errors are not mentioned) yourself.

• Shanz

Hi Devashish,

Yeah, if the user is actually sleeping they can't press 'y', but thats kind of the bad joke :).

Oh I see, so theres no way to bool a char.

• Alex

You could do this:

Alternatively, you could avoid using a boolean variable altogether:

• Shanz

Hi Alex,

Thanks so much, that makes a lot of sense. I was wondering if I didn't even need to use the bool, just not sure what I could use since I've only gotten up to the chapter for chars so far.

• himanshu

HEY ALEX!

IT IS RIGHT TO ADD THIS OPERATOR ">>"
TO COUT.....

HERE WHY AM ASKING THIS
YOU ADDED ">>" IN COUT IN ABOVE

'"
'"
AND ONE MORE QUESTION

IS IT POSSIBLE TO CREATE OR DESIGN
SOMETHING LIKE FACEBOOK AND WHATSAPP ...

AND ALSO IN MY CODEBLOCKS 16.01 WHEN I COMPILE YOUR ABOVE ANSWER WITHOUT INT MAIN THERE A
ERRORS COME SAYING "cout does not name a type" "expected unqualified id before if and else".

• Alex

No, that was a typo on my part. I've changed "cout" to "cin" as intended.

> IS IT POSSIBLE TO CREATE OR DESIGN SOMETHING LIKE FACEBOOK AND WHATSAPP …

Given that these things exist, I'd say yes, it's possible. But if I were going to develop the next Facebook, I'd probably use something other than C++.

My code above is a snippet, not a full program. You'll need to #include iostream if you want to compile it, so the compiler knows what cout and cin are.

• some guy

I'm confused as to why you make the IsEqual function a bool, wouldn't making it an int function work just as well? Or is it declared as a bool function so you have an idea of what the return values will be and what the function does? Sorry if I sound like a newbie :p

• Alex

IsEqual function isn't a bool, it returns a bool. Boolean values are used to represent values that can only be true or false. When we're talking about whether a value is equal, either it is (true), or it isn't (false). Consequently, it makes more sense to return a bool than an int. While technically returning an int would work (returning the value 1 if the parameters are equal, and 0 otherwise), returning a bool is more intuitive and leaves less room for errors to be made.