Language Selector

2.6 — Boolean values and an introduction to if statements

The next data type we’re going to look at is the boolean data type. Boolean variables only have two possible values: true (1) and false (0).

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

When assigning values to boolean variables, 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:

When boolean values are evaluated, they actually don’t evaluate to true or false. They evaluate to the integers 0 (false) or 1 (true). Consequently, when we print their values with cout, it prints 0 for false, and 1 for true:



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

This prints:


A first look at booleans in if-statements

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

if (condition) statement


if (condition) statement
else statement2;

In both forms, condition is evaluated. If condition evaluates to true (non-zero), then statement is executed. In the second form, if condition evaluates to false, then statement2 is executed instead.


b is true

Boolean values are also useful 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. hasCommonFactor).

In the following example, we use the equality operator (==) to test if two values are equal. Operator== returns true if the operands are equal, and false if they are not.

Note that in C++, a single equals (=) is the assignment operator, whereas a double equals (==) is a comparison operator to test for equality.

In this case, because we only use equal in one place, there’s really no need to assign it to a variable. We could do this instead:

Boolean variables are quite refreshing in their simplicity!

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


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

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

  • some guy

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

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

  • programmer

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

    like this example:

    if i want to ask some one about his car ?

    bool car;

    is the above good solution or not ??

    i’m witing for your answer

    thank you so much

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

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

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

      • Shanz

        Hi Alex,

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

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

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

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

        • Devashish

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

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

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

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

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

          • Shanz

            Hi Devashish,

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

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

        • Alex

          You could do this:

          Alternatively, you could avoid using a boolean variable altogether:

          • Shanz

            Hi Alex,

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

  • another_programmer

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

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

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

  • Kiran

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

    • Ashish Gupta


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

      For futher query you can ask me..on

  • Spock

    Hey Alex,

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

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

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

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


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

  • Noha

    In which cases do we use the implicit assignment?

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

  • someone

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


  • joel

    Great Tutorials, well written and structured. many thanks.

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

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

  • Sam

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

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

    for the program to read

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

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

    • Collin

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

  • Alex

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


    • Daniel

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

  • Stephan

    Hi Alex (Admin)!

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

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


  • Mac

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

    return (x == y == z)

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

    after i took away “int z” it worked just fine…

    does bool only work for two variables?

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

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

  • Guntis

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

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

  • joha

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


  • gurbux

    hey nice explanation alex very helpfull………..

  • xero

    I want to ask why following code works?

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

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

  • John


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

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

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

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

    I hope I’m making sense here!

    • Alex

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

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

  • Carol

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

    #include <iostream>
    using namespace std;

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

    int main()
        cout << "Please enter a 1-digit number." << endl;
        int myNumber;
        cin >> myNumber;
        if (isPrime(myNumber))
            cout << "The digit is prime" << endl;
            cout << "The digit is not prime" << endl;
        return 0;

    • Alex



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

  • Daniel Ricci

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

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

  • Tito

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

    • Matthew

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

  • Melissa Arredondo

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

  • Snowman

    I think I took the quiz too seriously =P

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

  • Rich S.

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

    • Alex

      It sounds like you’re doing something like this:

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

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

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

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

    • cpplx

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

  • programmer, another one

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

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

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

    for example:

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

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

    Thanks for the reply, and for building this amazing website

    • Alex

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

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

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

  • Brian

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

    • Alex

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

      • Brian

        • shakey2

          line 12:

          should be

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

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

  • Vishal

    Hello Alex,

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

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

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

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

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

    Please enlighten me! 😛

    • Alex

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

      equal equal == true
      true true
      false false

      Therefore the “== true” part is redundant.

  • shakey2

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

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

    • Alex

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

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

  • Tree Stan

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

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

    • Alex

      It’s a good question.

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

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

  • In the above program, everything before "bool bothZero(false) ;" works fine. But when I run the whole program and input the value zero (0) for both x and y, the else statement is executed and outputs "But both the numbers were not zero." and when I input a non zero number for either x or y, my program outputs " Both the numbers were zero. " and if the given non-zero numbers are equal, It results "But both the numbers were not zero. " .

    When I do this with my program :

    It works fine with value 0 for both x and y but even when I input non-zero but equal numbers for both x and y, program still outputs the same "Both the numbers were zero. " . What is the problem. Please give a fine version of this program. My program is supposed to take two integer numbers from user. If both the numbers are zero, it should print "Both the numbers were zero. " and if user inputs 0 for either x or y, I want to print "But both the numbers were not zero. " Everything except this part of the program runs fine so I am not including the output given by rest of the program.

    • Alex

      Does not do what you’re assuming it does.

      This evaluates as “if ((x == y) == 0)”, which will only be true if x and y are different numbers, and has nothing to do with whether either is 0.

      The easiest way to fix this is to use the logical AND operator:

      We cover logical AND (and other logical operators) in the next chapter.

  • This works fine…please explain how.

    • Alex

      This isn’t a C++ question -- it’s a logic question, which you should be able to work out for yourself. :)

      • Thank you so much Alex for these tutorials. Now at least I know why my codes above were working and not working. I can see how bad I was coding a few months ago. Probably, I would never do these type of mistakes in my future programs. You made me write better codes and m still learning. Someday if I get a job, I’ll miss your contribution. You are helping me to be a better programmer day by day. You are doing a great job.
        Thanks Alex…

  • Methos

    I came up with the following (main just calls these functions in order) and while I’m feeling a little clever, I thought I’d ask if any of this is a truly terrible idea.

    I called a function from inside itself as a check the user actually put in an appropriate value that unwinds whenever he finally cooperates. Also I used the fact that the prime comparisons are mutually exclusive to macgyver an ‘or’ check on the variable’s primeness (though I think based on what you’ve said I could get away with a sum like this for an ‘or’ so long as the number of conditions is small enough not to run into overflow issues).

    • Alex

      Cool solution! None of these is truly terrible.

      However, I do have a few suggestions for you:

      * Recursion is useful when the solution to a problem can be calculated by using the result from a subset of the problem. That isn’t really the case here. A do-while loop would be more appropriate. This is covered in chapter 5.

      * Instead of using + in primeCheck() (which is clever), use the logical OR operator (||). It’ll make it clearer what your intent is, as well as be more efficient due to short circuit evaluation. This is covered in chapter 3.

      * Give your variables better names. :)

  • radiz

    Hi, can you explain why i can’t use boolean datatype in a loop condition like this, please?

    • Alex

      You can use a boolean datatype in a loop condition like that. However, your program has errors that will prevent it from working correctly:
      * You never assign a value to “input” before you use it in an expression.
      * Your loop variable (condition) is never changed, so your loop will either not execute at all (if condition is false), or go into an infinite loop (if condition is true).

      Remember that variables can only hold values, not expressions.

  • person

    So, if the if statement is true than the else statement after it is always ignored?

    Where is it decided in your solution that if prime is true that the if statement will be chosen?

    • Alex

      Yes, the else is ignored if the if statement condition is true.

      > Where is it decided in your solution that if prime is true that the if statement will be chosen?

      I’m not sure I understand the question.

      This is the code that checks if prime is true, and prints “The digit is prime” if it is.

      • person

        It’s difficult to explain what I mean.

        If prime is false why does it jump past if directly to else?

        What establishes that prime must be true for the if statement to be chosen?

      • person

        I think I understand now.

        Prime can be false but still be a variable called “prime”, so I didn’t see a reason why the if statement couldn’t be satisfied whether prime was true or not because the answer will be the variable “prime” regardless.

        However, I realize that the compiler sees it not as the variable named prime, but rather as a boolean 1 or 0.

        True prime is different from false prime because 1 is not equal to 0.

        • Alex

          Right. prime is a variable that can hold two values: 0 (false) and 1 (true). Our program uses logic to determine whether variable prime is set to true or false.

          We then use an if statement to determine which of two statements executes based on whether we set variable prime to true or false previously.

  • Yujian


    I dont understand why u used false instead of true in line 12. Why cant we use true instead of false there?

    are u doing this because of we have to assume that everything is false at the start and then classify those who are not?

    • Alex

      The comments in the quiz answer show the logic behind this choice:
      // We start by assuming the user did not enter a prime number
      // Then we test to see if they did

      If we started with prime = true, then how would prime get set to false if the user didn’t enter a prime number? We _could_ do that with an else statement at the end of the if/else chain, but the logic is slightly messier that way. I like trying to keep the number of if and else statements to a minimum.

      > are u doing this because of we have to assume that everything is false at the start and then classify those who are not?

      We don’t have to do it this way, but it’s easier to enumerate all the cases where prime should be set to true than where it should be set to false.

  • Yannick

    So I tried the quiz and at my first attempt I got the same answer as you do but after that I wanted to find something to not use else if 3 times and I got this, but for some reason I cant build it and I can’t find my mistake.. btw this is the error i get:
    1>---- Build started: Project: primenumberOrNot, Configuration: Debug Win32 ----
    1>  primenumberOrNot.cpp
    1>LINK : fatal error LNK1168: cannot open C:\C++ Projects\primenumberOrNot\Debug\primenumberOrNot.exe for writing
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • Alex

      It sounds like your executable has either been flagged as read-only or locked for some reason. Is it possible you have an instance of it already running when you’re trying to compile?

      In the worst case, restarting your system will probably resolve this.

  • Mr D

    Thanks, amazing tutorials!

    I’m having a hard time getting my head around the initialization of bool.

    Consider the program i wrote below. As it stands, it outputs the correct answer. However, if i change the first "false" to "true", it outputs the opposite answer! Why does it matter how the bool is initialized? Why doesn’t the compiler believe the statement "if (45 == x) what = true;"?

    • Alex

      If you initialize “what” to true, then how would it ever get set to false if 45 does not equal x? If you’re going to invert the initialization, you also need to invert the if statement that sets “what” to true.

      Also, “what” is a pretty poor name for a variable. A name like “equals” would be easier to read.

  • R00kie


    I am trying to figure out something in the 2 codes you wrote :


    It is clear that the bool function returns a boolean value (true/false), but why x == y means true ?

    You never defined x == y as being true ? so how does the compiler assigns the "true" value when x == y ?

    The operator == does all the work , and returns "true" ? I ask this because "true" or "false" were never defined in the function …

    I wrote the same code like this , as it makes more sense to a newbie like me . Is my code incorrect or redundant as I see the compiler not complaining  ??


    The 2nd code is in your Quiz

    Why is "prime" considered true in the "if statement" when the value of true was not assigned in that if statement ?

    I wrote my code like this :

    So in my "if" I specifically assigned the "true" value to "prime"  ? But how does the "if" in your code knows that "prime" is "true" by default ??

    It picks up the value of "prime" from here ?? from x == 7, prime = true ???

    I am trying to figure out the logical aspects of your code, and to understand why the compiler executes your last "if statement" with "prime" being true by default ?

    • Alex

      true and false are keywords in the C++ language, so C++ knows what these two things are without us defining them.

      1) In this code:

      The == operator does all the work. It compares x and y to see if they are equal. If they are equal, it evaluates to true. If they are not equal, it evaluates to false.

      2) It’s not clear to me what you’re actually asking here. Prime is a variable, so it has whatever value was last assigned to it. Also, don’t mix up operator= (assignment) with operator== (equivalence).

      The program works by initially setting prime to false as a default value. Then the program checks to see if x is equal to 2, 3, 5, or 7. If so, prime is set to true. Otherwise, prime still has the value false.

      When we get down to here:

      prime has already either been set to true by the if/else statements above (depending on the value of x), or has been left at the default value of false.

      The program evaluates prime to see what value it has (true or false, as set above) and conditionally executes the appropriate output statement.

  • Gayan

    #include <iostream>

    bool isPrime(int x)

        return (x==2||x==3||x==5||x==7);

    int main()
        using namespace std;
        cout<<"Enter a single digit integer! "<<endl;
        int x=0;

        bool Equal=isPrime(x);

            cout<<x<<" is a Prime number ! "<<endl;
            cout<<x<<" is not a Prime number ! "<<endl;

        return 0;

    What about this? :)

  • Phil

    I might be getting ahead of myself here but you state that boolalpha is part of the iomanip header but as far as I can see it is included in iostream. If I comment out the

    line in your example it compiles and runs just fine.

    • Alex

      Actually we’re both wrong (but you’re more correct than me). :) boolalpha is included in the <ios> library. But <iostream> #includes <istream>, which #includes <ios>, so #including <iostream> is sufficient. I’ve fixed the article.

  • Joseph

    Hey, I am getting errors on lines: 13, 15, 17, and 19.
    They state: term does not evaluate to function taking 1 arguments expression preceding parentheses of apparent call must have (pointer-to-) function type.
    Which I am only sending one parameter so I don’t know why term doesn’t evaluate to function taking one argument. Not to mention the rest of the error message is going above my head.
    Also a warning message stating: an empty control statement was found (line 18).

    Any way you can demystify this for me?

    • Phil

      With the statements prime(true); on lines 14, 16, 18 and 20 the compiler thinks you are calling a function named prime with one argument "true" whereas you are trying to assign a value 0f "true" to the variable "prime". You need to use the assignment operator "=".
      So the lines

      should read

  • Aroma

    Hi, Alex
    After several attempt at what I was trying to do, I got my answer from the reply you gave to "Tree Stan" on lesson 2.6 on this page. I was trying to use (x==2,3,5,7) in my code which C++ does not parse it in the way I intended. Thanks to the introduction of the "||" operator. I used it and my code runs well now.
    But am  a bit confuse about the boolean  in the solution provided to the quiz, in the statement: [if (prime) cout<< "The number is prime"; else cout <<"The number is not prime"; ] Now my question is why does the output  always remain "The number is prime" when the user input any number immediately I change the "prime" to "true" ?, thus making it : [ if (true) cout<< "The number is prime"; else cout <<"The number is not prime"; ]

    • Alex

      > Now my question is why does the output always remain “The number is prime” when the user input any number

      It shouldn’t. Variable prime should only be set to true if the user enters a prime number, and it should only print “the number is prime” if variable prime is true. If that’s not happening there’s an error in your code somewhere.


    i am very newbie and i got up to this chapter…as per my understand i came up to this solution…but only prints out this is prime no. please advise why this is wrong…

    here i was trying to do was first assigning x to prime no. ans later calling bool sdprimeNo function to print “this digit is prime no.if it = to x defined in sdPrimeNo else not a prime digit…. please help tnx.

    • Alex

      This will compile, but it won’t do what you want. It’ll assign x the value of 2, which is then converted to the boolean value true, and returned to the caller.

      The best way to do what you want is to compare the value of x to each target value independently (using an if statement) to see whether it matches or not.

  • Scott

    I’m confused about something:

    The former program will print "You did not enter 2" even if 2 was actually entered. The latter program works fine.


    • Alex

      Yup. This will happen on compilers that define int8_t as a typedef of char. On those compilers, int8_t will behave identical to char.

      In the above program, when you enter 2, std::cin sees that you’re entering a char, so it interprets your 2 as the character ‘2’ instead of integer 2. Character 2 is ascii code 50, so x = 50 in the top program.

  • Alec Garcia

    When I did the quiz I did it this way without == I understand both ways but what is wrong with this. I mean it works with the compiler..

    • Devashish

      Compiling this program is error free because your code is syntactically valid, logically invalid. expression x = 2,5,7,9; will be evaluated as x = 2; Reason: the comma operator. The comma operator (covered in 3.4) resolves to it’s right most operand that is 2 in this case. Thus 2 is assigned to x and rest of the literals are discarded. Again, 9 is not a prime number, thus should be removed from the list. Your function primeNumber() doesn’t care of the value passed in. It always returns false (0). If user entered 2,3,5, or 7, the program will print “x isn’t prime”. That’s not expected. If you want to make this program shorter (don’t want to write too much), then do this:

    • Alex

      What’s wrong with it is that it doesn’t work. If you enter 5, it tells you that 5 isn’t prime, but it is.

  • This is an easier way to make the quiz.

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

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

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

  • 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

    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.

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

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

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

  • Viktor

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

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

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

  • 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

    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?

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

  • Xprog

    It was my solution and it seems to work

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

    do you have the same website in C language please ?

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

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

  • T

    Many many thanks for this site Alex!!

    Here’s my solution, which seems to work

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

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

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

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

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

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

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

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

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

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

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

  • metr1xx

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

Leave a Comment

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




3 + 11 =