Search

2.6 — Boolean values and an introduction to if statements

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: “Apples are a fruit”. Is this statement true or false? 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.

Boolean variables

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

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).

Consequently, 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:

This prints:

1
0
true
false

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

A first look at booleans in if-statements

One of the most common uses for boolean variables is inside if statements. If statements typically take the following form:

if (expression) statement1;

or

if (expression) statement1;
else statement2;

When used in the context of an if statement, the expression is sometimes called a condition or conditional expression.

In both forms of the if statement, expression is evaluated. If expression evaluates to a non-zero value, then statement1 is executed. In the second form, if expression evaluates to a zero value, then statement2 is executed instead.

Remember that true evaluates to 1 (which is a non-zero value) and false evaluates to 0.

Here’s a simple example:

prints:

The condition is true

Let’s examine how this works. First, we evaluate the conditional part of the if statement. The expression “true” evaluates to value 1, which is a non-zero value, so the statement attached to the if statement executes.

The following program works similarly:

prints:

b is false

In the above program, when the condition evaluates, variable b evaluates to its value, which in this case is false. False evaluates to value 0. Consequently, the statement connected to the if statement does not execute, but the else statement does.

A slightly more complicated example

The equality operator (==) is used to test whether two integer values are equal. Operator== returns true if the operands are equal, and false if they are not.

Here’s output from one run of this program:

Enter an integer: 4
The value is non-zero

Let’s examine how this works. First, the user enters an integer value. Next, we use operator== to test whether the entered value is equal to the integer 0. In this example, 4 is not equal to 0, so operator== evaluates to the value false. This causes the else part of the if statement to execute, producing the output “The value is non-zero”.

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 one run of this program:

Enter an integer: 5
Enter another integer: 5
5 and 5 are equal

How does this work? First we read in integer values for x and y. Next, the conditional expression “isEqual(x, y)” is evaluated. This results in a function call to isEqual(5, 5). Inside that function, 5 == 5 is evaluated, producing the value true (since 5 is equal to 5). That value is returned back to the caller. Since the conditional evaluated to true, the statement attached to the if executes, producing the output “5 and 5 are equal”.

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!

Non-boolean conditionals

In all of the examples above, our conditionals have been either boolean values (true or false), boolean variables, or functions that return a boolean value. What happens if your conditional is an expression that does not evaluate to a boolean value?

You already know the answer: If the conditional evaluates to a non-zero value, then the statement associated with the if statement executes.

Therefore, if we do something like this:

This will print “hi”, since 4 is a non-zero value.

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: 119

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 and didn’t assign a value to b. Consequently, when std::cout printed a value for b, it printed whatever uninitialized value was in variable b. Garbage!

Quiz

1) A prime number is a whole number greater than 1 that can only be divided evenly by 1 and itself. Write a program that asks the user to enter a single digit integer. If the user enters a single digit that is prime (2, 3, 5, or 7), print “The digit is prime”. Otherwise, print “The digit is not prime”.

Hint: Use if statements to compare the number the user entered to the prime numbers. Use a boolean to keep track of whether the user entered a prime number or not.

Quiz answers

1) Show Solution

2.7 -- Chars
Index
2.5 -- Floating point numbers

363 comments to 2.6 — Boolean values and an introduction to if statements

  • Felipe

    How do you close "std::cout << std::boolalpha;"? same as other similar examples shown in 2.5 and what are best practices.

  • Felipe

    "they don’t actually don’t evaluate to "true" or “false” " error you didn’t catch 🙂

  • James Ray

    Hi Alex,

    Just some minor feedback.

    You said "Let’s example how this works." I think you mean to use examine rather than example.

    Also, you said:

    ---

    Here’s a simple example:

    prints:

    the condition is true

    ---
    Technically, the output should be:
    The condition is true

  • Skyler

    If code reads top to bottom can I have three outcomes or no?

  • Jeff

    In the last section (2.5) you said we should start utilizing int8_t (fixed width) instead of int or long.  When I try to do that, though, the char type makes the value input by the user the ASCII value. So the non-prime number 6 turns into 54.

    I saw a comment above about static cast, but that only changes the way the number is output to the console, not how it’s interpreted by the machine.

    So… should I not use fix width since I’ll get the wrong values since visual studio interprets it as a char…?

    • Alex

      Yeah, most compilers treat int8_t the same as char, which means std::cin and std::cout treat it as a char instead of an integer. As far as I’m aware, the only way to std::cin an int8_t is actually to cin an int and then cast it to an int8_t.

      e.g.

  • Skyler

    Let’s say I wanted to change the return value example to compare full equations what would I have to change in order for it to operate properly.

    • Alex

      I’m not sure what you mean by “compare full equations”?

      • Skyler

        I want a program that lets you enter an equasion (e.g. 23+4) and compare it to another (e.g. 123-75) and it tells me if its equal or not.

        • Alex

          If you want the equations to be of arbitrary complexity (multiple operators) then that’s an intermediate level task. If you only want to support one operator and two operands, you can have the user enter both sets of equations and then manually handle the operator. Basically, it’s like writing a calculator program that takes two sets of input, produces two separate outputs, and then compares if they are equivalent.

  • At the quiz, why does the last ‘return false;’ work? Wouldn’t the function return true at first but then end up returning false before the function quits?

  • Herbert

    I think all numbers except 0 are "true" in C++, 0 is "false".

    bool b = false;
    std::cin >> b;
    // entering 199
    ->> b is true

  • OT Young

    So for the quiz portion I made my program by using lots of "else if"s so it looked kinda like this:

    It actually looked almost exactly like that, I hope I used the code tags right…
    But the program ran fine, I’m just wondering what is a good practice when making these kinds of programs
    (or more importantly more complex programs)

  • M

    Hello Alex, I absolutely love your tutorials.

    You should be aware that on Stackoverflow.com there is a post which has garnered 4262 upvotes - it is a list of the best books to learn C++ from (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). I bought the top rated book and moved through about 150 pages of it - I’m not going to lie, it was pretty dry. I am roughly a 4th year university student and have a decent handle on Java and am now learning C++. Your website blows the best rated book out of the water. Nothing against the book (C++ Primer), but you have a vastly superior tutorial here. your explanation is simple, not verbose, easy to grasp, and contains an element of humor (which only the best teachers have).

    I am sure you are sick of hearing compliments, but I hope you acknowledge that your work is incredible - and this is the opinion of someone who has read a programming textbook or two…

    Thanks a ton… You are a wonderful human! Thanks.

    • Alex

      Thanks for the complement! I can’t take all the credit though. If the site is good, it’s because the content been honed by thousands of readers who took the time to help improve it by pointing out my technical mistakes, typos, sloppily written sentences, grammar errors, and content omissions. 🙂

  • Rafael

    My question is really straightforward, when can I use boolean in the following forms:
    bool something ()
    {
       >code<;
    }

    and
    bool something ();

    In your quiz both versions are used. When I try to use the first, it always says that I am missing a semicolon and thus must be in the format of the second.

    • Alex

      The first is used when you’re defining both a function and the function body (in essence, defining the function in its entirety). The second is a forward declaration used to tell the compiler that a function exists, but is defined somewhere else (in another file, or somewhere later on in this file).

      The first should work just fine -- that’s how you declare a function, so something else must be going on. I’m not sure what though.

  • Silt

    Oops… I accidently wrote a programm, that calculates prime numbers, with one ore more digets, instead of writing them down ^^
    Was fun though

  • Abdullah Sheikh

    i want to check the color
    For example I am generation random colors but the most repeating color is red. I am also asking from user if the color is red then press 1 and it is not then press 2.
    The basic problem to how to check is user is answering the correct answer or not. So what can i do.
    Sir I am not a programmer but a student.

  • Matt

    Good evening!  The following code is what I came up with when I went into this problem before showing your solution.  Specifically, my question is about the 4th line of code inside main().  

    I did not declare a bool variable like you did, I just sent the user input directly to a function that spits out a bool return - and since my solution is what I came up with without your help I’m concerned I’ll do the same thing in the future.  Is what I did wrong, or just another way to skin the same cat?  Ultimately the function works as intended, just wanting to double check myself.

    Thanks!
    Matt

  • marcomayday

    How wrong am I? Can’t figure out the proper code =(

    • Alex

      Your program seems to work, so at least there’s that. However, there’s some room for improvement:
      * Function isprime() should take a bool parameter, not an int (this better signals your intended usage)
      * Calls to isprime() should use arguments true or false, not 1 or 2
      * isprime should return void

  • Roman

    Hello Alex, thank you for these tutorials.
    Is this acceptable to write all functions’ calls in the one statement?

  • kanishk

    Hey Alex… i just wanted to know ,in line 13 of the solution of quiz

    can be replace false with zero since  false evaluates to 0??

  • Braden Baker

    When you use the program

    the output is listed as
    b is true
    but it should say
    The condition is true
    Just so you are aware :p

  • Dan

    Hi Alex, hi Earl,
    I just read this page and was also wondering if the solution really works…
    Maybe replacing

    in line 6,8,10,12 with

    ?

    Thank you for this tutorial, I find it clear and I can read it for hours without getting tired!

  • Earl

    This is the way i can get it around to work. But for some reason when i choose the number 3 it tells me that this is not a Prime number, else is correct. Is this a good way to do it? Or if i follow your solution the prime is stated undefined. Is there a book for your work i can purchase? your work has really helped me a lot, appreciate it thanks =)

    • Alex

      This doesn’t work for a few reasons. But the primary reason is that the function never returns prime in the cases where prime is set to true.

      If you want to do things this way, you should declare bool prime before the if statements, not redeclare it within the if statements, and return prime at the end of the function.

  • Earl

    I have been lost for days. I kept repeating the quiz and for some reason the "prime = true" im getting in the bool function seems to be undefined. i start over again and again i still kept getting Error: identifier "prime" is undefined. As last resort even copying your solution on my work and i still getting the error. It seems to me that somehow the “bool prime = isPrime(x)” in the main isn’t functioning. Some enlightenment please. I am using VS2013

    • Alex

      Sorry, this one is my fault -- I missed a line when copying the example from my compiler into the lesson. I’ve updated the example now and it should compile.

  • PencilFriend

    Alex,

    I also struggled with the last ‘if’ statement for a long time. I think that the difficulty people are having with it is that the switch from numbers to words (true/false) activates the verbal reasoning part of the brain causing readers to, well,…read.

    So when we get to the final if statement our minds read it verbally,"If (false) then print "the digit is prime" makes perfect sense verbally; equally, "If (true) then print "the digit is prime".

    It would help to say explicitly: the "if" statement in c++ code is checking for the value "true". If "if" does not receive the value "true" the "then" statement will be activated.

    As you have introduced the "if" and "then" statements under the heading of "Boolean values" it may seem obvious to someone with a mathematical background that "if" will somehow be related to "true". But for most of us who have become proficient in verbal reasoning before coding, it is difficult to read the words in the code and make the switch to evaluating mathematically.

    Even though I now know what the "if" statement is checking for (because it is code, and not a word) I still have to read it the first way, and then remind myself. It is like seeing ‘the man in the moon’…once you see him, he won’t go away!

    I would like to say that this is the first time I have been stuck; the lucidity of your explanations is admirable.

    Thank you,
    PencilFriend

    • Alex

      I’ve updated the lesson fairly significantly, including more examples and explanations of how things evaluate. Let me know if you think this is a step in the right direction.

      • PencilFriend

        Alex,

        I don’t know…how can you not like asparagus? 😉

        The current presentation seems much improved from my perspective, for what that is worth.

        These portions are particularly helpful:

        1) When used in the context of an if statement, the expression is sometimes called a condition or conditional expression.

        In both forms of the if statement, expression is evaluated. If expression evaluates to a non-zero value, then statement1 is executed. In the second form, if expression evaluates to a zero value, then statement2 is executed instead.

        2)In the above program, when the condition evaluates, variable b evaluates to its value, which in this case is false. False evaluates to value 0. Consequently, the statement connected to the if statement does not execute, but the else statement does.

        Thank you for being a conscientious teacher! There are never enough of those because the process is so effortful. I am grateful for the prompt reply and careful consideration given to my comment.

        PencilFriend

  • Ramon Bijl

    The part that confuses me is

    If prime = what? Wouldn't it be more logical to put

    ?

    • Alex

      The following two lines are equivalent:

      And we can prove it. Variable prime can only have two values: true or false.

      First, assume prime is true. “if (prime)” becomes “if (true)”, which evaluates to true. “if (prime == true)” becomes “if (true == true)” becomes “if (true)”, which evaluates to true. So when prime is true, both statements evaluate to the same thing.
      Now assume prime is false. “if (prime)” becomes “if (false)”, which evaluates to false. “if (prime == true)” becomes “if (false == true)” becomes “if (false)”, which evaluates to false. So when prime is false, both statements also evaluate to the same thing.

      Therefore, since we’ve shown that both statements evaluate to the same thing for every possible value, they must be the same.

      It definitely looks funny seeing a boolean by itself, but remember that when evaluated, that boolean evaluates to a true or a false, just like a comparison using the == operator does.

      • Ramon Bijl

        ah, so when we return 2 to the program it automatically says it’s false, then we check if it is false, if so print "The digit is prime"

        • Alex

          I’m not sure what you mean at all.

          • Ramon Bijl

            What i’m trying to say is that this is actually going on

            Am I right?

            • Alex

              Not quite. Boolean variables only get “replaced” with false or true when they’re evaluated to produce a value. So for this section of the program:

              We’re not evaluating prime to produce a value, we’re giving it a value, so there’s no replacement happening.

              Now let’s take a look at this statement:

              Here, prime does get evaluated. So we’ll end up with one of two cases:

              And that will evaluate to either true (former case) or false (latter case), which will cause the if or else statement to execute.

              This is no different from how int variables evaluate to produce a number.

              • Ramon Bijl

                alright so this is going on then

                • Alex

                  Yes. Just in this case, you’ve used logical OR to convert the 4 discrete if statements into a single if statement.

  • George

    Thanks.
    I’m pretty new to this domain and I just went to university where we study and learn programming algorithms.
    Do you know a tutorial for algorithms?
    I mean a tutorial that takes you from zero.

    Best regards,
    George

  • George

    Hey,
    Why do we need boolean data?
    I could use integer data as well with the same result and honestly it seems a bit weird when you put statements like "return (x == y);".
    It is more simple if instead that i would put
    if(x==y)
    {
    return true;
    }
    else
    {
    return false;
    }

    • Alex

      Are you asking why booleans exist when integers can do the same thing? If so, mainly because they do a better job modelling situations where the only results are true and false.

      For example, if I had this code:

      I could return a value of 1 to indicate x and y are equal and 0 to indicate otherwise, but that doesn’t tell me whether this function could return other values, like 2. If this function returns a bool, it’s clear that this function only returns one of those two values.

      Booleans also let you do boolean comparison nicely, whereas since any non-zero integer maps to “true” two “true” integers may not be equivalent.

      Boolean shortcuts (such as “return (x==y)”) may seem a bit strange at first, but once you get used to booleans you’ll love the conciseness.

  • alex do you have another website for java tutorial??

  • Kılıçarslan

    I came up with this.

  • Olvin Lizama

    Well looks like most of us thought in using a function to determine if the number was prime or not, that’s nice and means we are almost all in the same page, here is my result for the quiz, a few years later 🙂

    If you have any suggestion will be much appreciated,

    Thanks for this awesome course!

  • Halar

    when i compile this program,complier show an error. Can you help me?

    #include<iostream>
    using namespace std;
    int main()
    {
    int x;
    cout<<“enter a number”<<endl;
    cin>>x;
    if(x>=0)
    {
    cout<<“the number is positive”;
    }
    else
    {
    cout<<“the number is negative";
    }

    return 0;  
    }

  • Rebecca

    Hi, this is the code that i wrote to test myself with your quiz,

    When comparing with your code in the solutions tab, i see that you used "if", then "if else", then "if else", Instead of just "if" and "if" and on and on, but i find that both my code and your code works, any reason behind ending "if" with an "else" each time? Thanks in advance!

    • Alex

      In this case (because the if statement bodies contain return statements), if and if/else should function identically. If they did not contain return statements, then they would function differently.

      I think if/else flows a little better logically -- it makes it clearer that these if statements are meant to be exclusive (only one can be true at a time), and that the else is a “catch all”. Your else is only attached to the if (x==7) case, which is a little odd -- it would actually be clearer if you removed the else altogether and just had return false; unconditionally.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter