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

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

  • Nicolas

    Hello Alex,
    I did the quiz and I got the following error:

    ---- Build started: Project: HelloWorld, Configuration: Debug Win32 ----
    1>main.obj : error LNK2011: precompiled object not linked in; image may not run
    1>C:VC2017ProjectsHelloWorldDebugHelloWorld.exe : fatal error LNK1120: 1 unresolved externals
    1>Done building project "HelloWorld.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========  

    Since I saw nothing wrong with my code(which I dont have cause I deleted it)  I copy and pasted your quiz answer and it still gave me the same error. Any idea why?

  • Hi again,

    I took a slightly different approach to the quiz as follows:-

    Although I may have overdone it a bit on the parentheses 😉 , ideally I would also like to have included a check on the input to make sure it was in range (between -10 and 10) to give the user an opportunity to start again, but that’s just me, I’m a belt and braces guy 🙂

    What do you think

    • Oops!, I’m sorry, I messed up, after checking a few sites about prime numbers I should have re-worded my comment about setting a range to say "in between 1 and 10", apparently, a prime number is a positive integer above 1 that can only be divided by 1 or itself (which makes sense)

      Sorry about that,

    • Alex

      I think this is great. I didn’t use this solution only because I haven’t talked about logical OR yet. But once you know what logical OR is, this is a better solution.

      • Dammit!, I’m sorry Alex,

        I was doing a tutorial called learn C++ in 21 days previously by some fella and freaked out when it hit classes, functions and overloading it’s one of those tutorials that starts simple but moves very fast (too fast for my old brain)

        I didn’t mean to introduce an advanced concept at this stage, I thought that the ideas in my listing had already been covered (e.g. forward declarations and logical operators) I am sorry about that.


  • the confused coder

    Hello, I can’t figure out why my code doesn’t function like yours does. When I build and run, I can type the 4 prime numbers and I can type any other number that isn’t and it always will display "this number is prime."
    Heres the code:

    Why is this happening?

    • Alex

      You have extraneous semicolons after your if statements:

      Otherwise it parses like this:

      • the confused coder

        Awesome, that worked thank you. And 1 more thing, could you explain why we add

        at the end of the bool statement?

        • Alex

          Consider how the logic of this function works. The user’s input must be either prime or non-prime. In this function, we test to see whether the user entered a prime number. If we’ve gone through all of the prime numbers and none of those matched the user’s input, then the number they entered must be non-prime.

          That return false at the end is the function telling the caller that the number must be non-prime, because none of the tests for whether the number was prime succeeded.

  • astro

    thanks for the tutorials. i have a slight problem, when entering the numbers 2,3,5 both texts "prime" and "no prime" are displayed in my program, for some reason it doesn’t appear on the number 7. non the less anyone have any suggestions.

    • Helper

      Your last if statement has else statement nested with in it. This causes anything to be not prime if it is not equal to 7

    • Kevin

      as "helper" said, ur problem is not putting the curly braces "{}" in each statement. Make sure to always use curly braces.

    • Alex

      This is happening because the else statement is only being attached to the last if statement, so it will always execute so long as a does not equal 7.

      You can solve this by using a series of if/else statements (if (a==2) … else if (a==3) … else if (a==5) … else if (a==7) … else …).

      A few other notes:
      1) Variable a in main() isn’t doing anything and should be removed
      2) Parameter a in instructions() should be a local variable, not a parameter (move it inside the function body)
      3) prime() should return void since you don’t return a value (or need to)

  • Timothy Davis

    just ignore the sleep thing, i just use it to keep the program open for couple secs so i can see what happens, anyways did i do my homework correctly teacher ?

  • Jim Smith

    This is my homework.

  • Stelios

    in the quiz why cant we just use int isPrime(intx)
    and why do you say return false in the answer of the quiz question

    • Alex

      You could use int as the return type instead of bool, but that doesn’t express your intent as well. You should use bool when you mean true/false, and int when you’re actually returning an integer value.

  • rick

    hey! 🙂

    first of all i gotta say - this tutorial is really awesome and i learn very much from it! 🙂 keep it up!

    so i did the quiz an i end up with a problem in my isPrime function that i do not understand. every number i pass seems to be a non-prime number 🙂 is it impossible to use || or && in if? :/

    here we go:

  • Kyle

    Hey Alex! Thanks for these tutorials. I’ve been noticing that while I can accomplish the end goal, I always write it much differently than you do. For example, I can’t make my mind think to have the isPrime() func just return true or false to main(), but instead I have isPrime() do all the heavy lifting.

    Is this a problem I should worry about that might cause issues down the road when I reach more complex stuff? I taught myself basic coding on those TI89 calculators, so I never had a good tutorial or rules to follow. Thus, the way I fundamentally piece my solution together in my head is… off.

    Also a side question: is it a bad idea to forward declare main() or to call it more than once like I have below (just added functionality to check more than one number)?

    Anyway, heres my code:

    • Alex

      Figuring out how to break down your program into functions is something that’s a bit of an art. It takes practice, and you’ll likely do it wrong many times before you learn how to do it right. Just keep practicing, and it will come with time. Remember the “functions should do one thing” guideline. Your isPrime() does two things: determines if something is prime, and then prints whether it is prime or not. That violates the “one thing” guideline.

      It is not a good idea to call main() more than once. If you want to have something execute more than once, you should generally use loops (covered in chapter 5).

  • Alana Howard

    I went about writing this code tooooootally unlike the answer, although the program was debugged and runs effectively, which is cool cause I was worried I would just rip my hair out before peeking at the answer.  I made a header file titled IsPrime which defines 4 variables w,x,y,&z as the single digit primes.  I included this in my "PrimeProgram.cpp"

    Is this way of doing it problematic and a bad habit that I don’t know I’m starting, or is it just a different approach that is okay to use?

    • Alex

      Yes, it’s problematic for several reasons, mainly because it doesn’t work. 🙂 If you enter 8, it says 8 is prime, when it’s clearly not.

      Outside of the not working issue, here’s other issues I’d identify as not good:
      1) You’re defining variables w, x, y, and z as global variables when that’s not necessary here. You could just use literal numbers 2, 3, 5, and 7 instead. The variables are extraneous.
      2) You also define v as a global variable and then shadow it with a local variable inside main (get rid of the global int v).
      3) You’re using the comma operator in a way that doesn’t make sense (chaining expressions via comma inside a conditional doesn’t do what you might expect).
      4) You’re using = instead of == in main() (setting w, x, y, and z to the user’s input instead of doing a comparison)
      5) You defined isPrime() but then you never call it.

      The overall structure of your program is good (have an isPrime function that returns a bool indicating whether the number is prime) and the top of your main is good, but things go sideways from there. Keep at it. 🙂

    • Alana Howard

      I guess the whole thing got sideways when the isPrime function gave various errors when I tried to call it, saying that it wasn’t allowed and incompatible with the bool function.  I’ll implement your suggestions and rewrite it(hopefully correctly) and hopefully it becomes similar to the given answer, if not almost identical 😀 I also should have checked the non prime numbers more thoroughly - when the screen printed it I just kind wishfully assumed I was reading "not prime" because I was so excited it was running at all. ^_^ Thanks for the help!

    • Alana Howard

      Okay, so after much brain wracking and having to reorganize to as simple as possible(difficult for me, I make all things complicated :)), this is what I ended up with, I tested each number to ensure it worked, and it does!  I was curious if the bool == instruction returns true if equal and false otherwise, is there a necessary reason that true and false were defined in the quiz answer?

      • Alex

        Yes, operator== returns true if the operands are equal and false otherwise.

        I wrote the quiz answer to be as easy to follow as possible for users still getting familiarized with bool, true, and false. Plus we haven’t covered logical OR yet. Experienced programmers would write isPrime() more like you did.

  • One Manual

    That solution is so $%&/%/$#%(**). In 1.4 Quiz (1e) it is implied that only one of 2 return values is returned, only the first one (5 in that particular point). Ergo i smashed my head in the keyboard trying to find a solution compatible with the things i have been learning.

    Apparently there CAN BE more than 1 return value in a boolean function. Im confused now.

    Also please point out that the program in this quiz doesnt have to take in account ALL the prime numbers, only the 4 written there.

    • Alex

      My apologies for your head and your keyboard. I updated the text of lesson 1.4 to try and clarify a bit better. A function can only return a single value back to the caller. However, the function can use whatever logic it wants to determine which specific value to return. It can pick a single value from a set of values, or it can use an if statement to conditionally return a value. I also updated the example in this lesson to better indicate this.

      I’ve also updated the quiz to be clearer that you only need to take into account the single digit prime numbers.

  • Felipe

    isn’t this better?

    • Alex

      Yes, experienced programmers would get rid of the temporary variable in this case and do as you suggest.

      My goal here is to try and make the solution as understandable as possible, not as efficient as possible. For that reason, I moved the call to isPrime() outside of the conditional.

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


    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.


  • 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 there is a post which has garnered 4262 upvotes - it is a list of the best books to learn C++ from ( 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 ()

    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.


  • 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


    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,

    • 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


        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.


  • 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

    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

    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
    return true;
    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?

    using namespace std;
    int main()
    int x;
    cout<<“enter a number”<<endl;
    cout<<“the number is positive”;
    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.

  • SeniorTrout

    alex first i want to thank you for your wonderful tutorial,
    second do you think that my code is right?

    • Alex

      No, and I can prove it. 🙂 Try it with input 5, and you’ll see that it produces the incorrect answer.

      Break your return statement up into multiple if statement, each returning true or false as appropriate, and you should be okay.

  • Tony


    A remark on this quote "One additional note: when converting integers to booleans, the integer zero resolves to boolean false, whereas non-zero integers all resolve to true." This is partial true. Officially a BOOL represents 0 for False and 1 for True. This is inherited from C. Other languages interpreted 0 for false and everything else - including negative values - for True. There are a lot of Microsoft API’s that mix those two options.

    • Alex

      Yes, bool false is stored as an integer 0 and bool true is stored as an integer 1, but what we’re talking about doesn’t concern other languages -- it concerns what C++ does when converting an integer to a bool. In that particular case, what I wrote is accurate -- integer 0 is converted to bool false, non-zero integers (which includes negative numbers) get converted to bool true.

  • Mike

    Can you help me out

    #include <iostream>

    using namespace std;

    bool primenumber(int a, int b, int c, int d) {

        return (a == b == c == d);

    int main() {
        cout << "Enter a prime number.." << endl;
        int prime;
        cin >> prime;
        bool prime = primenumber();
        if (prime == 2)
            cout << "its a prime number.." << endl;
        if (prime==3)
            cout<< "its a prime number.." << endl;
            cout << "its a prime number.." << endl;
        if (prime == 7)
            cout << "its a prime number.." << endl;
            cout << "Please enter a prime number.."<<endl;

        return 0;

    • Alex

      What logic are you trying to do here? You read in an integer from the user. Good. You call primenumber(), but I’m not sure why -- the number of arguments don’t match the number of function parameters, so this won’t compile. Then you check if the boolean result of that function is equal to an integer (which it will never be). Your else statement doesn’t make sense either.

      It seems like you’re mixing up your concepts. You should either be:
      1) Getting rid of primenumber() function and just checking if variable prime is equal to 2, 3, 5, or 7 and printing it’s a prime number, or
      2) User primenumber() to determine whether the passed in argument is prime, and returning that result as a bool. Then you can use that result to print it’s a prime number or not.

  • Pavel Hegler

    I am trying to check if the input number is prime;
    prime numbers are:
    can be divided evenly only by 1, or itself

    so this is my code:

    i get following errors on Microsoft Visual Studio 2015 Professional:

    1>---- Build started: Project: isPrime, Configuration: Debug Win32 ----
    1>  main.cpp
    1>c:\users\admin\desktop\01_serious_ learning\isprime\isprime\main.cpp(16): warning C4715: ‘isPrime’: not all control paths return a value
    1>c:\users\admin\desktop\01_serious_ learning\isprime\isprime\main.cpp(6): error C4700: uninitialized local variable ‘i’ used
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    i dont understand what is meant by uninitialized local variable ‘i’ used. Can somebody explain what am i doing wrong?

  • Mobo

    Hi Alex,

    Thank you so much I really appreciate. What an oversight on my path. Once again, thanks.

  • Mobo

    Hi Alex,

    First of all I will like to thank you for this tutorial, it has really helped me a lot besides you are an excellent teacher. I have a question regarding the quiz on prime numbers. I modified your solution to handle prime numbers in general. However, i observed that when I initialized prime with a false value, i got unreasonable results, but when I initialized it with a true value, i obtained realistic results (except for when x==1, which i have not catered for). I don’t think the value of the initialization for prime should have any effect on the results. Should it?

    • Alex

      Of course it should, given the way you wrote your code. Here’s your code in a nutshell:
      * prime = true
      * if any of these conditions are true, prime is false
      * print the value of prime

      So, if none of the conditions is true, then prime will retain its default value of true. If you set prime to false initially, then no statement will ever set it to true.

      If you want your program to be “default value agnostic”, then you probably need this statement after your last else if:

      This will ensure prime gets a value if none of the if statements above match.

  • x41822n

    Alex, first of all, thank you so much.

    Second, I prefer to use 0s and 1s for true and false values, is it a bad practice? Will it not work in some compilers etc-etc?

    For example this is my code:

    • Alex

      It will work with all compilers, but it’s not standard practice, and implies that other values may be possible (at least, until the user remembers that isPrime is a bool and not an int). You’re better off using true and false with boolean values, as they help reinforce that isPrime is, in fact, a bool.

  • Muhammad Junaid

    Hi Alex,
    please Alex guide me in this code that work in this way:

    1. When user enter alphabet or other than character on keyboard except digits than prompt the user to enter the correct value.

    2. When user enter digit than calculation(addition) would be done correctly by using these digits

    I solved this but islpha did’t work in this program when i use char data type than it work or stores the value in ascii value and result is not correct  but i didn’t want this.

    • Alex

      You really need to use a loop to accomplish what you are intending, so that you can ask the user to do something again if they do it wrong. We cover loops in chapter 5.

  • sdmv

    In the quiz program

    where you made the assumption

    instead if i write

    and ignore the false assumption the program results in all inputs being prime.
    why does this happen?
    Doesnt the else part supposed to be printed for all inputs that are not in if part? (I mean if ‘if’ statement evaluates to true doesnt the else statement automatically evaluate to false?)

    It also happens in my code

    This program results all inputs being prime
    But if i write the program like this

    The output is correct.
    What is happening in both these programs?
    Im confused here.Please help me through

    • Alex

      Defining a variable without an initializer allocates memory for the variable, but does not initialize the variable with a value. That means the variable “acquires” whatever value was already at the memory address that it got assigned to. This means your uninitialized bool prime could acquire the value of either false or true.

      My reference code works because prime always starts with value false, and then the code sets prime to true if (and only if) it determines that prime is true.

      However, in your top code, if prime acquires the initial value of true, and function checkEqual() only ever sets it to true, then there’s no case where prime could ever equal false. That means your code will always say the number is prime. Your checkEqual() function really should return false at the bottom, which would fix your issue (that way, prime would be set to false if the integer didn’t match 2, 3, 5, or 7.

      In your bottom code, your checkEqual() function will always return the value of (x==2). The other return statements never evaluate.

  • Damien

    Hi Alex,

    Thanks for these tutorials, they have been helpful and fun to go through so far.

    For the question in this section, i did mine a bit differently. Tried to mimic the same sorta method as in the chapter 1 review and the result is below. I have a couple questions if you have the time:

    - do you suggest following the same format for these questions as what was used in the chapter 1 review questions?
    - the code below works, but is there any bad habits you think could catch me out in future?
    - also when determining whether the user input number is prime or non-prime, instead of using all the if/else statement, is it simpler to just use "return x == 2 || x == 3 || x == 5 || x == 7;" as some others in the comments have done, or is there some disadvantage to this?

    P.S. i used uniform initialisation in some parts, no clue if it even makes any difference. I was just going on the suggestions from an earlier chapter/section, which gave a brief overview and said further detail would be in future chapter.

    Thanks very much for any help!




    • Alex

      > do you suggest following the same format for these questions as what was used in the chapter 1 review questions?

      Not sure what you’re asking by this

      > the code below works, but is there any bad habits you think could catch me out in future?

      A few nitpicks:
      * Give your variables better names
      * variable y should be a bool, not an int
      * In main, you’re initializing variables to 0 and then overwriting that value with some other value. You might as well combine these (e.g. int x = userinput()).

      > is it simpler to just use “return x == 2 || x == 3 || x == 5 || x == 7;” as some others in the comments have done, or is there some disadvantage to this?

      Yes, it’s simpler and better. I don’t use that solution here because we haven’t covered logical OR yet at this point in the tutorials.

  • Jimmy

    I have a different answer for the quiz.

  • Stavrogin

    Hi Alex,

    I read your book "Jumping into C++" couple of months ago, now i’m also reading your tutorial on the site. Both of them are of great work keep it up!

    For the Prime Number Quiz, I tried to come up with a more complicated answer, could you please glance over it a bit and advise if anything could be improved?

    Thanks & Regards.

    • Alex

      I didn’t write “Jumping into C++”. That was some other Alex. There are apparently a lot of Alexes who are into programming. 🙂

      First, some syntax issues. There’s no need to pass x into isPrime() since main doesn’t do anything with that value afterward. Just declare x as a local variable inside function isPrime().

      Second, I’m not sure the ruleOfPrime() function adds any value -- by definition, a number modulus itself is 0, and a number modulus 1 is 0, so this function seems tautological (it should always return true).

      Third, as I’m sure you know, this only works for numbers that have a greatest common denominator of 10 or less.

      But other than those things, I applaud you for going beyond the scope of the ask. Doing things like this is a great way to learn.

  • PsychoPat

    is this acceptable?? it’s working like it should…but it’s way different from the solution.

    • Alex

      It’s not working like it should. Try an input of 6.

      • PsychoPat

        Sorry I copied the wrong one… it was pretty late when i posted… but this one works for me

  • metr1xx

    I try to include the tips from before except multifile because it’s not necessary for that.
    My solution:

  • subh

    How is my code (good/bad)? It’s able to produce intended result, but shows below message:
    ||=== Build file: "no target" in "no project" (compiler: unknown) ===|
    ||=== Build finished: 0 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    #include <iostream>
    bool isPrime(int a)
      if ((a == 2)  || (a == 3) ||  (a == 5) || (a == 7))
        return true;
       return false;


    int main ()

        using std :: cout;
        using std :: endl;
        using std :: cin;
        int x;
        cout << "Enter a single digit number" << endl;
        cin >> x;
            cout << "x is prime" << endl;
             cout << "x is not prime" << endl;
         return 0;

  • joe

    I am having a little trouble understanding the quiz.

    How if when I set the original PRIME Boolean to false, does the final IF statement know that when I say IF(PRIME) that I am referring to the modified PRIME and not the original.

    I do not see the logical progression.

    • Alex

      Let’s use an analogy. Pretend that prime were a flag. The flag can be raised (true) or lowered (false). It initially starts lowered, but depending on what the program does, the flag may be raised. At the end of the program, we’re checking whether the flag was raised or not. The flag may still be in the initial lowered state, or it may be raised, or it may have been raised and lowered many times in between. When we execute “if (prime)”, it doesn’t matter what previous values prime had -- all that matters is what value prime has right now.

      Make sense?

      • joe

        I absolutely get the analogy.  That was not the problem.   The problem is how does the final IF know which prime is to be printed as the IF or the ELSE.

        If a prime was not input into the console, the prime stands as false, so when it comes to the IF/ELSE, it should print the digit is prime even if it is not.  

        Do IF statements default to IF is true, ELSE is false?  Because if that is so, I can understand the quiz.
        IF(true) print A. ELSE(false) print B.  

        Otherwise, I still feel stumped.

        • Alex

          Aah, sorry, I misunderstood.

          is an often-used shortcut for

          Which makes the intent a little more clear. If variable prime has the value “true”, then execute the statement after the if (otherwise, execute the else, if that exists).

  • Joshua2000B

    Is it not possible to include multiple lines of code within a specific if statement?
    The sample of code I had was

    And error over the "else" appeared, saying "expected an expression". This error disappeared after I removed the std::cout line from the IF section.

    • Alex

      Yes, you can put them in a block (inside { }).

      We talk about this more in chapter 4.

  • Andy

    Hello Alex. This was the first quiz in which I struggled a bit.
    In the end, by consulting some previous lessons as well as persevering I managed to fulfill the objective, a program that assesses if a number is prime or not by using bool.

    However when I look at the answer, I see you did it much differently. Was the method I used inefficient and/or inappropriate?

    • Alex

      This isn’t that much different than what I did. The main thing here is that since isPrime returns a bool, your return statements should return bool values as well (true or false instead of 1 or 0).

      Other than that, seems fine!

  • Nyap

    heres my program for the quiz:

    how could I improve?

    • Alex

      use true instead of 1 and false instead of 0 when you’re dealing with boolean values. It makes your intent clearer.

      Other than that, looks fine for now.

  • Zach

    I misunderstood the assignment, and gave it a go using some of my prior knowledge. I’ve tested it with several different numbers, and wondered if I could get some input on it.

    I used this function in place of the first if/else ifs you had in the solution.

  • Robbie

    #include "stdafx.h"
    #include <iostream>

    int userInput()

        using namespace std;
        cout << "  Please enter a digit: " << endl;
        cout << "  ";
        int x;
        cin >> x;
        return x;

    int primeTest(int input)

        if (input == 2, 3, 5, 7)
            bool prime(true);
            return prime;
            bool prime(false);
            return prime;

    void displayResult(int input, bool prime)

        if (prime)
            std::cout << "  " << input << "  is prime." << std::endl;
            std::cout << "  " << input << "  is not prime." << std::endl;

    int main()

        int input(userInput());
        bool prime(primeTest(input));
        displayResult(input, prime);
        return 0;

    Is this okay? I know it works, but I wonder if I over-complicated it…

    • Alex

      This shouldn’t work at all.

      “if (input == 2, 3, 5, 7)” may compile, but it won’t do what you expect.

      Otherwise, the structure is fine.

      • Robbie

        Okay, thanks Alex. One more question, what would be the correct way to express that in one line?
        I have seen people write if(something == value || value2 || value3 || value4) is that correct?
        Thank you in advance.

  • Igazi

    Thanks for the great tutorial Alex.
    Here is my solution. IT seems to work fine
    #include <iostream>
    int main()
       using namespace std;

       cout<<"Give a single digit integer"<<endl;
       int x;
       bool digit((x == 2) + (x == 3) + (x == 5) + (x == 7));
       if (digit)
       cout<<"The number is prime"<<endl;
       cout<<"The number is not prime"<<endl;
       return 0;

  • LebiTheCoder

    Hey Alex, I’m just confused. I wanted my code to be as brief as possible, so what I’ve done is:

    cout << "Enter Single Number" << endl;
    int x;
    cin >> x;

    bool prime (x==2, x==3 x==5, x==7);
    if (prime)
    cout << "PRIME";
    cout << "NAH";

    This is just a fragment of my code. I don’t want to call any function outside int main () because I believe that this is just a simple program. As expected, it doesn’t compile. And also, I don’t know the ‘else if’ so I’m having pretty hard time to create the code. Below, I’ve seen a comment that does this:

    bool prime(false);
        int number;
        cout << "Enter the number that you think is a prime number.. " << endl;
        cin >> number;
        if (number == 2 || number == 3 || number == 5 || number == 7)
            prime= true;
        if (prime)
            cout << "The number you entered is a prime number" << endl;
            cout << "The number you entered isn’t a primenumber" << endl;
        return 0;

    He/she uses || to seperate the conditionals. Can you explain this please?

  • Jim

    Several other users picked up on this!   We all noted that you used a function name and its parameters as the condition in the if statement above.. If (isEqual (x,y)).  That’s pretty unusual, I had no idea that this was allowed. Is this done very often in C++.

    I hope you’re going to cover the condition statement a bit more in later lessons. Newbies will be amazed what you can put between the parentheses.

    Thanks I learned something new!

    • Alex

      Yes, it’s common for functions that return a boolean value.

      It’s essentially the same as:

      Just without using a temp value.

      I cover if statements and conditionals more in chapter 4.

  • Domenic D

    I believe this is the result your looking for?

    • Domenic D

      Sorry just realized that we have not done loops in any detail. I have said this before, Love the pace and attention to detail you bring. Thanks again.

  • T

    Many many thanks for this site Alex!!

    Here’s my solution, which seems to work

  • Lee Jo

    Hi Alex,

    Thank you for this wonderful website. I started studying C++ using this site a few days ago and this is immensely helpful.

    I wrote a program for checking any integer for prime. It is working fine for any integer which is not a prime number and for prime numbers up to 2273. If I input 2281 which is the next prime number, it says that filename.exe has stopped working. (I use Visual studio Community 2015)

  • Thank you for replying !

    I am going to learn C++ even if it’s difficult to understand.

    NB: some people say if you want to learn c++ start by learning c the reason why i asked the question.

  • hi,Alex ?
    This website is great for starting programmers in c++

    do you have the same website in C language please ?

  • Xprog

    It was my solution and it seems to work

  • Garrett



    Get a undeclared identifier error for weapon

    • Garrett

      Different approach to the same issue, which returns an undeclared identifier error for Shield and Sword



    • Alex

      function main() is using a variable named Weapon but you never declare a variable named Weapon in a scope that main() can see (the Weapon inside function pickSwordorShield() can’t be seen by main()). Your main has a few errors as well. You probably meant to do this:

  • Sharaf

    and my last but not least the doubt is if you have made a statement as

    how do the prime knows whether if it is true it has to print prime if not prime(i mean if it is false) then it has to print not prime.

    • Alex

      prime can only hold the value true or false. It doesn’t know anything about what to print.

      The if statement is responsible for determining what is printed.

      The following code:

      is shorthand for:

      which in English translates to “if prime is set to true”.

      So the logic of the if statement translates to: “if prime is set to true, then send the string “prime” to be output. Otherwise, print “not prime”.

      Make sense?

  • Sharaf

    i didn’t understand if u have declared the variable as

    then how can you make its value as

    maybe i didnt understand bool variable

  • Sharaf

    what is the use of bool here can you explain thanks!

    • Alex

      I don’t see any explicit uses of bool here, so I’m not sure what you’re asking.

      Ideally, the return value of equ() should be a bool, as should the type of variable equal.

      • Sharaf

        i mean what is the use of bool here

        i mean what is the use of bool  here in my program if i can compile it without use of bool

        • Alex

          To indicate that the expected values are boolean.

          While you could use an int (or a double, or any number of other crazy things), you should use the concept that best maps to what you’re trying to do. For an “is” statement (is x equal to y?), there are only two outcomes: true or false. So a boolean is the most appropriate data type.

  • Viktor

    Hello, when testing the boolalpha identifier(?) I had to write:

    If i didn’t it told me it was undefined.
    Full program:

  • ThePixelCoder

    JUst saying that your examples have some bad practice. They use members of namespace std yet you write them without the std:: before the member. This is okay if you write using namespace std; at the top of the code but you might want to fix it because it can probably trip some new coders up.

  • hi everybody here i am being arrogant if i say i am a newbie, modestly i may say iam a -since three days cpp learns -  
    i decided to learn cpp after my modest html tutorial .

    i do never know anyother information about programming but after i downloaded code::blocks and after reading this long list of  coments i decided to be partof this community, but i ll be through exams soon , so don t expect a very interaction with you.

    ah about the prime number 2,3, 5,7.  i came with this idea
    i ll type it , i assure it worked for me .

    #include <iostream>
    using namespace std;
    int main () {
           int r;
           cout << ". enter a single digit to check its being prime or not : ". << endl ;
          cin >> r;
          if (r!=2 &&  r!=3 &&  r!=5 && r!=7  &&  r <=7) { cout << " it is not prime " << endl ;}
          else if ( r >7) { cout << " invalid input " << endl;}
          else { cout  << r << " is prime " << endl ; };
          return 0;

  • Alex


    is the same as:

    And in this case, it’s clearer that variable x goes out of scope at the end of each condition statement.


    is a valid syntax for variable initialization but not for variable assignment. Since you’re trying to do a variable assignment here (you declared the variable above the if statement), this is not allowed.

  • Chris

    I am curious about this 2 code, why both of them doesn’t work?

    First code

    ||=== Build: Debug in test4 (compiler: GNU GCC Compiler) ===|
    D:\Eldon\CBProjects\test4\main.cpp||In function ‘int main()’:|
    D:\Eldon\CBProjects\test4\main.cpp|10|warning: unused variable ‘x’ [-Wunused-variable]|
    D:\Eldon\CBProjects\test4\main.cpp|12|warning: unused variable ‘x’ [-Wunused-variable]|
    D:\Eldon\CBProjects\test4\main.cpp|14|warning: unused variable ‘x’ [-Wunused-variable]|
    D:\Eldon\CBProjects\test4\main.cpp|16|warning: unused variable ‘x’ [-Wunused-variable]|
    D:\Eldon\CBProjects\test4\main.cpp|18|warning: unused variable ‘x’ [-Wunused-variable]|
    D:\Eldon\CBProjects\test4\main.cpp|20|warning: unused variable ‘x’ [-Wunused-variable]|
    D:\Eldon\CBProjects\test4\main.cpp|22|error: ‘x’ was not declared in this scope|
    ||=== Build failed: 1 error(s), 6 warning(s) (0 minute(s), 0 second(s)) ===|

    Second code :

    ||=== Build: Debug in test4 (compiler: GNU GCC Compiler) ===|
    D:\Eldon\CBProjects\test4\main.cpp||In function ‘int main()’:|
    D:\Eldon\CBProjects\test4\main.cpp|13|error: no match for call to ‘(std::string {aka std::basic_string<char>}) (const char [4])’|
    D:\Eldon\CBProjects\test4\main.cpp|15|error: no match for call to ‘(std::string {aka std::basic_string<char>}) (const char [4])’|
    D:\Eldon\CBProjects\test4\main.cpp|17|error: no match for call to ‘(std::string {aka std::basic_string<char>}) (const char [6])’|
    D:\Eldon\CBProjects\test4\main.cpp|19|error: no match for call to ‘(std::string {aka std::basic_string<char>}) (const char [5])’|
    D:\Eldon\CBProjects\test4\main.cpp|21|error: no match for call to ‘(std::string {aka std::basic_string<char>}) (const char [5])’|
    D:\Eldon\CBProjects\test4\main.cpp|23|error: no match for call to ‘(std::string {aka std::basic_string<char>}) (const char [5])’|
    ||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    Thank you.

  • rauny

    The integer-equivalents of 10111000 in the sign-magnitude representation and the 2’s complement representation are ‘x’ and ‘y’ respectively. Then, what is the absolute value of ‘x-y’?
    plz answer…

  • Chris

    we can’t add more statement in if-statement without parentheses, isn’t it?
    maybe you should tell the reader, we can use the parentheses in if statement so we allow to add more statement before or after ‘else’.

    maybe you should add form of if statement, this form.

    if (condition)

    or something like that. i get confuse when i didn’t know this method before i googled it. i just want to help so readers don’t get confuse like me. sorry if i had mistake and sorry for my bad English.

    • Alex

      We cover if statements (and blocks) in much more detail in chapter 4. I didn’t want to get too complex here since the focus is on boolean values.

  • AmnesiaMaster28

    I’m attempting to make a calculator thingy and using a bool to ask the user what calculation type they want, (addition or subtraction)

    I have a problem on line 20.
    I get this error.
    "expression preceding parentheses of apparent call must have (pointer-to-) function type" (by the way, what does this mean?)
    But if I add a "bool" before "add", the compiler complains for multiple initializations.
    How do I get around this?

  • Joao Lopes

    What do you think about this solution?

    • Alex

      I like the overall structure, but you use int where bool would be more appropriate in several places (the return type for verifyPrime, and the type of variable y in main), and you use 0/1 instead of false/true.

  • This is an easier way to make the quiz.