5.2 — If statements

The most basic kind of conditional branch in C++ is the if statement. An if statement takes the form:

if (expression)


if (expression)

The expression is called a conditional expression. If the expression evaluates to true (non-zero), the statement executes. If the expression evaluates to false, the else statement is executed if it exists.

Here is a simple program that uses an if statement:

Using if with multiple statements

Note that the if statement only executes a single statement if the expression is true, and the else only executes a single statement if the expression is false. In order to execute multiple statements, we can use a block:

Implicit blocks

If the programmer does not declare a block in the statement portion of an if statement or else statement, the compiler will implicitly declare one. Thus:

if (expression)

is actually the equivalent of:

if (expression)

Most of the time, this doesn’t matter. However, new programmers sometimes try to do something like this:

This won’t compile, with the compiler generating an error that identifier x isn’t defined. This is because the above example is the equivalent of:

In this context, it’s clearer that variable x has block scope and is destroyed at the end of the block. By the time we get to the std::cout line, x doesn’t exist.

Chaining if statements

It is possible to chain if-else statements together:

The above code executes identically to the following (which may be easier to understand):

First, x > 10 is evaluated. If true, then the “is greater” output executes and we’re done. Otherwise, the else statement executes. That else statement is nesting an if statement. So we then check if x < 10. If true, then the “is less than” output executes and we’re done. Otherwise, the nested else statement executes. In that case, we print the “is exactly” output, and we’re done.

In practice, we typically don’t nest the chained-ifs inside blocks, because it makes the statements harder to read (and the code quickly becomes nested if there are lots of chained if statements).

Here’s another example:

Nesting if statements

It is also possible to nest if statements within other if statements:

The above program introduces a source of potential ambiguity called a dangling else problem. Is the else statement in the above program matched up with the outer or inner if statement?

The answer is that an else statement is paired up with the last unmatched if statement in the same block. Thus, in the program above, the else is matched up with the inner if statement.

To avoid such ambiguities when nesting complex statements, it is generally a good idea to enclose the statement within a block. Here is the above program written without ambiguity:

Now it is much clearer that the else statement belongs to the inner if statement.

Encasing the inner if statement in a block also allows us to explicitly attach an else to the outer if statement:

The use of a block tells the compiler that the else statement should attach to the if statement before the block. Without the block, the else statement would attach to the nearest unmatched if statement, which would be the inner if statement.

Using logical operators with if statements

You can also have if statements check multiple conditions together by using the logical operators (covered in section 3.6 -- logical operators):

Common uses for if statements

If statements are commonly used to do error checking. For example, to calculate a square root, the value passed to the square root function should be a non-negative number:

If statements can also be used to do early returns, where a function returns control to the caller before the end of the function. In the following program, if the parameter value is negative, the function returns a symbolic constant or enumerated value error code to the caller right away.

If statements are also commonly used to do simple math functionality, such as a min() or max() function that returns the minimum or maximum of its parameters:

Note that this last function is so simple, it can also be written using the conditional operator (?:):

Null statements

It is possible to omit the statement part of an if statement. A statement with no body is called a null statement, and it is declared by using a single semicolon in place of the statement. For readability purposes, the semicolon of a null statement is typically placed on its own line. This indicates that the use of a null statement was intentional, and makes it harder to overlook the use of the null statement.

Null statements are typically used when the language requires a statement to exist but the programmer doesn’t need one. We’ll see examples of intentional null statements later in this chapter, when we cover loops.

Null statements are rarely used in conjunction with if statements. However, they often unintentionally cause problems for new or careless programmers. Consider the following snippet:

In the above snippet, the user accidentally put a semicolon on the end of the if statement. This unassuming error actually causes the above snippet to execute like this:

Warning: Make sure you don’t accidentally “terminate” your if statements with a semicolon.

Operator== vs Operator= inside the conditional

Just a reminder that inside your if statement conditional, you should be using operator== when testing for equality, not operator= (which is assignment). Consider the following program:

This program will compile and run, but will always produce the result “You entered 1” even if you enter 0. This happens because x = 0 first assigns 0 to x, then evaluates to the value 0, which is boolean false. Since the conditional is always false, the else statement always executes.


If you need a variable in an if-statement, but not outside, you can use an init-statement before the condition.

fullName is accessible in the entire if-statement, including its bodies. init-statements were added to the language in C++17.

5.3 -- Switch statements
5.1 -- Control flow introduction

147 comments to 5.2 — If statements

  • Thanks for making free education website.

  • sky helms

    [int add(int x, int y)
        return x + y;
    int main()
        int a ;
        a = 0;
        int b;
        b = 0;
        std::cout << "You are walking down an old hallway." << std::endl;
        std::cout << "You come to the end of the hall. " << std::endl;
        std::cout << " There are two doors." << std::endl;      // this is the introduction of the customised story
            std::cout << "Door 0 " << std::endl;
            std::cout << "And Door 1" << std::endl;
            std::cout << "Which way will you go?";
            std::cin >> a;
            std::cout << add(a, b);
            if (b = 0)
                std::cout << "You go left. and there is more hallway" << std::endl;
                std::cout << "after a few twists and turns you come to three doors." << std::endl;
                    std::cout << "Door 2" << std::endl;
                    std::cout << "Door 3" << std::endl;
                    std::cout << "Door 4" << std::endl;
                    std::cout << "Which way this time?";
                        std::cin >> a;
                    std::cout << add(a, b);
            if (b=1)
                std::cout << "You go through the door." << std::endl;
                std::cout << "You hear a rumble behind you." << std::endl;
                std::cout << "The door dissappeared and was replaced by a wall!" << std::endl;
                std::cout << "You are trapped in a box!" << std::endl;
                std::cout << "The roof slowly closes in on you!" << std::endl;
                std::cout << "You feel as your ribs give way" << std::endl;
                std::cout << "You died (Ending 1)";

        std::cin.ignore(32767, '\n');
        return 0;
    } ]
    umm i tried this and it only gives you the door one route help!

  • felipe

    Great job, just a few things I think you missed.

    isn’t this best practice:  return (x > y) ? y : x;


    shouln’t ErrorCode be a class?

  • B1

    hi Alex
    i have a question
    let's say i want to direct the user input based on the contents he write
    like this

    int input;
    string input;// i know i can't name the same name for more than one
    it's only for demonstration

    if (input != integer )
    cin >> input;
    getline(cin, s_input);

    how to tell C++ i mean numbers or a string as a class or a group ?

  • Matthew Morrissette

    ok so i want to do a thing where enter either (Y/N) into x then if (x==Y)
        goto this
    if (x==N)
        goto that
    invalid response

    but it sees Y and N as variables not as values any help would be appreciated :)

  • Janek Kondzior

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

    using namespace std;

    int main()
        int y;
        int x;
        cout << " what year were u born in ? " << endl;
        cin >> x;
        cout << " Your age is " << 2016 - x << endl;
        cout << "what number month were u born in ? " << endl;
        cin >> y;
        if (y == 1)
            cout << " You were born in January " << endl;
        if (y == 2)
            cout << "You were born in February " << endl;
        if (y == 3)
            cout << "You were born in March" << endl;
        if (y == 4)
            cout << "You were born in April" << endl;
        if (y == 5)
            cout << "You were born in May" << endl;    
        if (y == 6)
            cout << "You were born in June" << endl;
        if (y == 7)
            cout << "You were born in July" << endl;
        if (y == 8)
            cout << "You were born in August" << endl;
        if (y == 9)
            cout << "You were born in September" << endl;
        if (y == 10)
            cout << "You were born in October" << endl;
        if (y == 11)
            cout << "You were born in November" << endl;
        if (y == 12)
            cout << "You were born in December" << endl;

        std::cin.clear(); // reset any error flags
        std::cin.ignore(32767, '\n'); // ignore any characters in the input buffer until we find an enter character
        std::cin.get(); // get one more char from the user
        return 0;
    What did i do wrong?

  • A

    Line 12: inclusive should be exclusive
    Line 14: is greater than should be is greater than or equal to

  • Andrew

    Please, who knows C++ well, tell me, if if statements works like this:
    string x;
    cin >> string;
    if (x==hello || x==hi || x==1) {}

    My compiler does an error but how could I compare string variables like this? Or maybe Im not allowed to use "||" statement twice?
    Help me please, I liked C++ when I just saw this website but I still have some troubles.

  • bert

    In your first two "Nesting If Statements" examples, wouldn't the line:

              std::cout << x << "is greater than 20\n";

    also be printed if x is equal to 20? And similarly for x=10 in the third example? In that case, the printout isn't strictly correct.

    • Alex

      Without context, between can be used inclusively or exclusively. I meant it in the inclusive sense here. I've updated the lesson to explicitly note the inclusiveness.

  • Jane Doe

    0 is not negative. Also it works with the sqrt() why not include it? Was it not allowed in earlier versions of C++?

    • Alex

      I'm not sure what you mean. The code includes 0.0 in the set of valid input:

  • Domenic D

    Anyone want a challenge? Here try this ! It will flex your mental logic muscles.

    The program should hide the number the program selects and the user has 10 tries to guess the number from 0-1000. The program should tell you after each guess if you need to pick a high or lower number.

    Now the hard part! Your program should keep track of your low and high guess. However as the user guesses more guesses the high and low best guesses should adjust according to the users guesses.

    eg. lets say the program picks 300 and the user guesses 500 out of a range of 0-1000 the program will reply back "...lower"
    However the program now has to keep track of your best or closest high and low guesses.

    Sounds easy? You try it!

    disclosure: I don't have the answer as I am at the time banging my head on the keyboard lol

  • Joshua Richards

    Hi there Alex,

    I just always wanted to spot something missed that we learned from you that was inconsistent && that no one else has mentioned yet so here is mine.

    In the example where you are instructing that you can use if statements with logical operators starting with the and (&&) operator, and the or (||) operator, your code reads:

    else if (x > 0 || y > 0)
       std::cout << "One of the numbers is evenn";

    but wouldn't it actually be:

    else if (x > 0 || y > 0)
       std::cout << "At least one of the numbers is evenn";

    since the logical OR operator evaluating to true  means that one or both statements (assuming there are only two) are true?

    Also, thank you so much for taking the time to construct this material. You tutorials are by far the best I have came acrost o the internet thus far, you make the material so easy to understand and it's obvious that you very carfuly considered your structure and the proper order to learn the material, it all just works so well. Thnak You so much!

    • Alex

      Your logic around how logical OR works is correct -- however, what you're missing here is that this is an else if statement, and else if only executes if the original if isn't true. So consider:

      The first if statement checks if both numbers are positive. If so, the rest of the if else chain never executes. So if we reach the else if statement, it must be true that both numbers are not positive! Given that there are only two numbers in this case, and we know both aren't positive, if either one is positive then it means only one is positive. So we can definitively say only one is positive in this case.

  • saeid

    hi ALEX .i followed you tutorials and i learned so much about C++ from you (So thanks about this). from this point on i start coding your examples in my own way whit method's which i learned from you . this is your example :

    and this is my code :

    i'm grateful if you correct my mistakes or tell any suggestion.

  • Gemparks

    Hello there,

    Just to clear up the thing that has been bothering me all this time

    Is the following

    equivalent to this

    or this

    Or is there any other difference that i am not aware of?
    Thanks in advance

    • Alex

      None of the above are identical.
      In the top example, the two statements are independent (the execution of the first one doesn't impact the execution of the second one).
      In the middle example, the two statements are conditional. The second statement will only execute if its expression is true AND the first statement didn't execute.
      The the bottom example, the two statements are conditional. The second statement will only execute if its expression is true AND the first statement did execute.

  • Sourav jadhav

    how to understand the logic behind any c++ program. can anyone help me out with the loops!

  • can you help me with my homework. Create a program that will input a number and will display the number is odd or an even number.  SAMPLE OUTPUT:  Enter a number: 5
    That is odd number. please I've been doing my homework for 8 hours and still having a hard time. I will gladly appreciate if you will help me thanks and God bless you.

  • Te KA

    in section "Common uses for if statements", second example.

  • sara

    can anyone help me
    i want to know how to do dry run

    • Darren

      Don't go out when it's raining?

    • Mike Slay

      "Dry run" is an expression from bricklaying. You lay out the bricks for a row without mortar to see how they fit (a dry run). If you need to cut a brick in half, it's better to know in advance so you can put the half-brick near the middle. Otherwise you don't find out that one of the bricks needs to be cut until you're near the end. Having the cut brick near the end is weaker and looks funny.

      I know, that's two snarky replies with nothing you can use, but at least this one's interesting.

  • Note my comment. This program only prints something if user inputs a value greater than 10. But user was never asked to do so. If user inputs a value less than 10, program prints nothing and user can't figure out why it doesn't work.

    • Alex

      Yes, correct. This is something you wouldn't want to do in a real program, but the point of the program is to show how use of parenthesis disambiguates a dangling else case.

      You'll note in the next example we add an else case to the outer if statement.

  • Kanchana

    Dear Alex,
    It seems you are updating the whole tutorial. That's nice and thanx for that. I would like to make a little suggestion.
    If you could add a little note mentioning which parts were updated with the updated date that would be very much helpful for us.


  • Arnab

    I'm trying to write a code that that takes a no. from the user another no. from the user in the same line & any one of these operators (+ - * / %) beside the second no.& gives the result as output. How do I do this? Note: the user must be able to do this 5 times in a go.

    • Alex

      1) Since the user has to be able to do this 5 times, use a loop to allow the user to do this more than once. The loop can call a function.
      2) The function should ask the user for input, and then use an if statement (or switch statement) on the operator to give the result.

      This question is pretty similar to a question I asked in the chapter 2 comprehensive quiz, just with a loop so it executes more than one time.

  • Jake

    "Without the block, the else statement would attach to the nearest unmatched if statement..."

    Hey (not sure if you still check comments), but shouldn't the indentation of your 'else' statement(?) indicate which 'if' it belongs to? I understand the use of parentheses to aid in readability, but is that also the case for indentation in this regard?

  • Alam

    hello everyone
    i have a problem .it compiles even but never prints either of the code.just prints "press any key to continue".why so?

    #include // for sqrt()

    void PrintSqrt(double dValue)
    using namespace std;
    if (dValue >= 0.0)
    cout << "The square root of " << dValue << " is " << sqrt(dValue) << endl;
    cout << "Error: " << dValue << " is negative" << endl;
    int main()
    return 0;

    • megablocks

      You created a function, but never called on it in your main() so nothing is being executed.
      int main()
      double myValue = 2.0;
      return 0;

  • ericofilho

    Hi. I didn´t understand this example in chapter 6.7

    if (pnPtr)
    cout << "pnPtr is pointing to an integer.";
    cout << "pnPtr is a null pointer.";

    I don´t know what´s the condition for the if statement.

    Thanks in advance.

    • Alex

      "if (pnPtr) ..." is the same thing as "if (pnPtr != 0) ..." due to the way boolean values evaluate.

      This probably is a little easier to understand if you're not used to the shortcut syntax:

  • sethradio

    How do you check if a char variable equals a certain character?

  • astronaut13

    Is it possible for you to set more than one required parameter for the 'if' statement to pass? Such as - to see what attack a player chose and if they have the ability to use it?

    • Yes it is, though your example is bad, as it can be done with a single if parameter.
      but here's an example -

      bool something (bool a, bool b)
      { if ( a == true && b == false )
      { do something();
      return true;

  • iammfa

    where is my bug in my code:

    another thing i can't do:
    can i press my choose 1 or 2 without press enter key?

  • Rubinco Nineski

    I think that learn from this way of explanation is very directly, whithout hesitating...
    I read books for C++, but I spend time more than ussual, because no colours , no tabels,and no
    orders of information like in your wwww. Maybe the books must be in electron formats for faster
    learning and training, with colours and pictures..
    THANK YOU...

  • James

    Hi, i am a bit confused.

    If nValue is negative, and the function returns ERROR_NEGATIVE_NUMBER. How do you know its an error?

    Because ERROR_NEGATIVE_NUMBER could = 3 right?

    So when calling this function, if you wanted to make sure there was no error you
    would do sometihng like

    if (!DoCalculation(9)) {


    • James

      sorry, I accidntly posted before I was finnished writing. What I was saying is Wouldn't the error codes be the same as correct output?

      So how would know if the output was an error or an answer?

      or are error code usually more obscure, like ERROR_NEGATIVE_NUMBER = E-0f96

      just going off the previous lesson about enums.

      Hope this makes sence, sorry I might be way off!

      • Quinn

        Actually you're pretty accurate, the example is rather ambiguous on this point, but it wasn't meant to be usable code. ERROR_NEGATIVE_NUMBER would have to be a value that would not normally be returned by DoCalculation. For example, since DoCalculation does not accept negative numbers, it most likely doesn't return negative numbers, therefore in that case ERROR_NEGATIVE_NUMBER could be -1.

        • Alex

          I've updated the example to make it more comprehensive.

          Returning an enum error code works if:
          * The error code is the only return value (e.g. the function would have otherwise returned void).
          * The error codes are defined to be numbers that the function can't normally return (e.g. the error codes are all negative numbers, and the function would otherwise return only positive numbers).

  • Louie Hancock

    Hi, great website btw!
    However, whenever i try to use a char variable in an if statement (e.g :

    if(a = "Hello")
    cout << "Hello there";

    it does not compile correctly.

    can anyone help? if so please email me on or leave a comment

    many thanks

    • First off, = is for assignment, not comparison. You would normally use == to do comparisons, except == doesn't work on string literals (which is anything inside double quotes). Probably the best way is to declare your a variable as a std::string instead of a char. Then it will work as you expect.

      • J3ANP3T3R

        Hey alex just a quick clarification. when a compiler implicitly makes a block if none is declared it will only do so for the first single line statement ? in the example below it will create a block for "return ERROR_NEGATIVE_NUMBER;" and will not include "return ERROR_SUCCESS;" ? thanks.

        ErrorCode doSomething(int value)
            // if value is a negative number
            if (value < 0)
               // early return an error code
                return ERROR_NEGATIVE_NUMBER;

            // Do whatever here

            return ERROR_SUCCESS;

        Hey wouldn't it be a blast if you could add a chat section to your website :D ? where we all can collaborate and help each other out with minor questions. for those who are online. i am really new to C++ and i have a ton of questions that would have been considered spamming and could bloat your database.

Leave a Comment

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