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:



If you want std::cout to print “true” or “false” instead of 0 or 1, you can use std::boolalpha:

This prints:


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;


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:


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:


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!


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
2.5 -- Floating point numbers

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

  • Samira Ferdi

    Why you use return false in bool isPrime function?

  • Bennhyon

    Hi! I've been learning C++ here the last 2 days and i think i'm really making good progress thanks to you.
    I wanted to share the code i did for the exercise if you could tell me if that's a good thing for a first time.

    • nascardriver

      Hi Bennhyon!

      @sayIfPrime looks good, I made some changes to your @main function:

    • I think you should put the "you silly" comment right after they enter a number, and make them fix it.

  • Tony

    Hi Alex,

    What do you think of this solution?

    bool isPrime(int x)
        return (x == 2 || x== 3 || x== 5 || x== 7);

    int main()
        int x;
        std::cout << "Enter a single digit integer: ";
        std::cin >> x;

        if (isPrime(x))
            std::cout << x << " is a PRIME number!";
            std::cout << x << " is NOT a prime number!";

        return 0;

    I always forget that you can assign a function to a variable, so the only way I found out to do the exercice was this one^.

    Is that okay?

    • Alex

      This code looks great. I didn't use logical OR in my solution because it's not covered until next chapter.

      • Tony

        Thanks for the fast reply, Alex!

        Great tutorials, by the way. The best for c++ since it explains everything well and gives so many exercices (which many tutorials don't offer). These exercices are a freaking crucial point in learning this seemingly hard programming language. 😀

  • Gabe

    Hi me again,
    I don't really know where to ask this so...
    I want to be able to make my function return a text and I don't know how.

    • nascardriver

      Hi Gabe!

      I'll have to use content from future lessons for this since it hasn't been covered yet.

      Option 1:

      Option 2:

      Or don't return a string at all

      General issues with your code

      • Gabe

        Hello, I'm back
        I took a break from this because it was frustrating. I realized I could make my life easier and have qOne() return a boolean and have that boolean decided what main would output. But I can't seem to make qOne run then call the return value to use in main.

  • Getty


    My code looks some what different to the solution. Running from a previous lesson, I thought that it was bad practice to have anything within the main function, other than calls to other functions? I thought that it should be seperated. Here is my code:

    what would be the best practice / what would be expected if you was a software engineer?


    • Alex

      There's little point in having a main do nothing but call a single other function. In that case, you might as well put the logic in main.

      Most often in production code I've seen, main looks something like this:

      But since our programs don't tend to have initialization and cleanup needed, our main() can just be the contents of doWhatever().

  • Ali Dahud

    Hi Alex,

    why do I have to return false at the end of the function?

    • nascardriver

      Hi Ali!

      I assume you're talking about @isPrime.
      @isPrime has been declared to return a bool

      No matter what happens inside the function, it has to return a bool in every case (except when an exception is thrown)!
      If we were to remove the "return false;" and none of the numbers were matched @isPrime would not have a return value, this in turn would cause undefined behavior which, in the best case, causes a crash. Worst case, it works fine for you but crashes on other machines and you'll have a hard time figuring out why it's working for you but not for others.

  • nascardriver

    Hi siriusbuisness!
    Your compiler will generate the same output for both variants so there's no difference.
    However, when using an intermediary value you can view the variable in a debugger which is not as easy when using the return value of isPrime directly.

  • sirius buisness

    Hi Alex (and others)

    In my solution for this chapter’s quiz I used

    whereas you used an intermediary value

    Is the intermediary value better convention for if statements?

    Thank you for your time and the tutorials.

    • nascardriver

      Please edit your posts instead of re-posting them, the reply to your question is above.

    • Alex

      No, in most cases I'd write it as you did (unless I needed to save the result of the isPrime() call for later).

      I used an intermediary bool here just because it's a bit easier for learners to understand.

  • Karston

    Here's how I did it.
    What's the different between adding curly braces and no curly braces around the statement after if?

    • nascardriver

      Hi Karston!
      The curly braces are required if you want to execute multiple lines:



      Please use curly braces for readability and extensibility.

      To your code:
      Your isPrime function doesn't work
      (x / x == 1) Is true for any number, doesn't have an effect.
      (x / 1 == x) Is true for any number, doesn't have an effect.
      (x / 2 == 1) Is equivalent to ((x == 2) || (x == 3)) // 3, because (3 / 2) == 1. An int cannot hold 1.5 so it's floored to 1.

      Your program doesn't accept 5 or 7 as prime numbers, have another try.
      Initialize your variables.

    • Chakradhar Bhandaram

      If that condition"if" has only one statement, then there is no need of using braces there..

      But let's assume that u have more than a single statement, if you want them to execute only if the condition is satisfied, then u should go for curly braces..

      For a single statement it is not mandatory to keep braces

  • Riux

    Hey Alex!
    So I've tried to make a program that checks if a number is a prime.

    The problem seems to be that in checkPrime() it ignores the for loop that I've made, which results in wholeDivisions always being equal to 0.. What am I doing wrong?

    • Riux

      Hey Alex!
      I managed to fix it myself 😀
      My mistakes were:
      1. In my for loop I wrote:

      but it should be:

      2. I started

      at 0, which resulted in dividing by zero.
      3. And I don't quite get this one: I made 'input' and 'i' integers which for some reason made my program treat division1 like and integer (5/2 = 2, for example). I fixed that by making 'input' and 'i' floats. But could you explain why it was treating division1 like an integer?
      So yea now it works 🙂

      • nascardriver

        Hi Riux!

        When you divide an int by and int the result will be an int. As you figured, this can be fixed changed by having the dividend or divisor being a float.
        I don't know how the result type is determined so I wrote a test program.

        This produces the output

        It appears the result will be of the type of the dividend or divisor with the highest precision. (int < float < double)

        PS: Please edit your posts instead of deleting and re-writing them.

        • Riux

          Thanks nascardriver :D!
          So if the result will be of the type of the dividend/ divisor with the highest precision, then that means that I could only change 'i' into a float and leave 'input' as an integer and the result would still be a float right?

          And I'm curious does deleting and rewriting your comments cause problems? I mean I will obviously stop deleting them now but I'd just like to know.

          • nascardriver

            Correct, but don't loop floating point numbers unless you have a good reason to do so. Instead, cast one of the variables to a float while doing the calculation:

            You'll learn about casting in lesson 4.4a, if you think this is overkill for now you can keep doing it with floating point numbers in your loop but you shouldn't get used to it.

            Here's the comment problem:
            - You post
            - UserX presses reply and starts writing their comment
            - You delete and repost
            - The comment entered UserX cannot be added as a reply, because the original post doesn't exist. The reply will be published as a regular comment and you won't receive a notification.

            • Riux

              Great thanks a lot!
              I think I'll keep my method for now.. maybe I'll change it after 4.4a.
              And thanks for explaining the comment problem 🙂

        • Alex

          > I don’t know how the result type is determined so I wrote a test program.

          I cover this in lesson 4.4 under the subsection, "Evaluating arithmetic expressions".

          You're basically correct, but the list in that lesson is a little more comprehensive.

  • Monika Konadu

    Dear Alex,

    thank you very much for your helpful tutorial.

    I’ve got a question about the following little program:

    When I enter 1 it says "The input is true.", and when I enter 0 it says "The input is false.", as expected. What I wonder about is that the program takes every number, even negative numbers and fractions as true, except those that begin with 0. And every letter is considered false. I thought that if I don’t enter 0 or 1, "input" would be any random number because it wasn’t initialized. But why is then every letter false and every number true except 0?

    • Alex

      In C++, bool is an integral type, meaning your input is treated as an integer. That means integer 0 is treated as false, and other integers (including negative ones) are treated as true.

      Letters are invalid inputs in this context, and cause no input to be assigned to your variable. Thus, input remains uninitialized. This will cause undefined behavior when you use it later (to compare against false or true).

  • Weckersduffer


    Thanks for your excellent work with this great site.

    What do you think about this answer to your quiz?

    • Alex

      Honestly, it's not that great (but that's okay, that's how we learn). Here's why:
      1) calcu and calcu2 have horrible names. I don't know what they do without looking at the code. They could also be combined since they essentially exist to serve the same purpose.
      2) The logic you're using in main() isn't obvious. It really needs a good comment.
      3) Your program produces the wrong result when the user enters 2.
      4) You don't need to test for user == 9 since this should be covered by calcu2().

  • Weckersduffer

    When I run this code:

    And I write a decimal number, it runs infinite times.

    Thanks from Spain,


    • nascardriver

      Hi Weckersduffer!
      A quick recap of for-loops:
      A for-loop consits of three parts: for (p1;p2;p3)
      p1: This will be executed only one time before the loop starts.
      p2: This will be executed every time before the loop cycles. If this is true, the loop will run, if it's false the loop will stop.
      p3: This will be executed after every loop cycle.

      You are setting y to 5 right before the loop starts.
      Then you are checking if y is bigger than 4, which it is, because it's 5.
      Now your code inside the loop is executed, but y remains at 5.
      After your code has been executed, y will be increased by 1, now y is 6, which still is bigger than 4.
      What I'm trying to say is, you're increasing y but never decreasing it. All you're checking is if y is bigger than a certain value. This is what's causing the loop to run for an infinite amount of cycles.
      (It's not actually infinite it will stop at some point, you shouldn't worry about it just yet)

      I'd like to tell you what you need to change to make your code work, but I don't know what you are trying to do.

      • Weckersduffer

        Thanks for the answer, nascardriver.

        What I was trying to do was the code to run infinite times. So I write an integer, I obtain the answer, and then the code starts again, so I can repeat the process. This way, if I want to enter more than one number, I don´t have to press "F9" each time.

        Merry Christmas

        • nascardriver

          In that case you can use a while loop


          More about loops in chapter 5.5 onward.

    • Alex

      There are two issues here.
      1) Your program runs infinite times no matter what.
      2) When you write a decimal number, that's invalid input for an integer. std::cin goes into "failure mode". I talk about how to address such issues in lesson 5.10.

  • merocom

  • Abdulrahim Rana





    Sir, Why this is not printing "Authenticated" or "Unauthenticated"...?

    • Tim K.

      (Scope.)  verifyAuth() cannot access the values assigned from main() because you didn't pass any arguments to the function - like: "verifyAuth(acc, pin)".

      These are where your problem areas are:
        line 12 in main.cpp
        line 5 of verify.h
        line 3 of verify.cpp
        line 5 of verify.cpp

      Good luck!

  • Dear teacher, please let me ask your judge on following answer to your quiz.


  • Lucian Cati

  • Dear Teacher, could you please add << std::endl in snippet

    Also in (last) snippet


Leave a Comment

Put all code inside code tags: [code]your code here[/code]