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 lesson 5.7 -- 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

148 comments to 5.2 — If statements

  • hmmm

    hello there. i want to ask about my if else if statement.why does the output only show the first "if" even user type another input?? could anyone explain why?
    #include <iostream>
    #include <iomanip>
    #include <cstring>
    #include <string>

    using namespace std;

    int main()
        //variable declaration//
        char cusName[30], typeOfDev[15], problemType[5];
        char process;
        double itemPrice;

        //user id//
        cout << "---------------------------------WELCOME!!----------------------------" << endl;
        cout << "----------------------BRAINYTECH SERVICE CENTRE-----------------------" << endl;
        cout << "Name : " ;
        cin.getline(cusName,30) ;
        //input desktop//
        cout << "Enter type of device code : ";
        if (strcmp(typeOfDev, "DD") || strcmp(typeOfDev, "dd"))
            strcpy(typeOfDev, "Device Desktop");
            cout << "Enter problem type code : ";
            if (strcmp(problemType, "SI") || strcmp(problemType, "si"))
               strcpy(problemType, "Internet Security");
                itemPrice = 150.00;
            else if (strcmp(problemType, "SM") || strcmp(problemType, "sm"))
               strcpy(problemType, "Microsoft Office");
                itemPrice = 90.00;
            else if (strcmp(problemType, "MV") || strcmp(problemType, "mv"))
               strcpy(problemType, "Vertical Line");
                itemPrice = 200.00;
            else if (strcmp(problemType, "MB") || strcmp(problemType, "mb")){
                strcpy(problemType, "Black Spot");
                itemPrice = 200.00;
            else if (strcmp(problemType, "CH") || strcmp(problemType, "ch"))
                strcpy(problemType, "Hot CPU");
                cout << "Enter the process [M] maintain [R] repair : ";
                cin >> process;
                switch (process)
                    case 'M':
                    case 'm': itemPrice = 80.00 ;
                    case 'R':
                    case 'r': itemPrice = 87.00 ;
            else if (strcmp(problemType, "CG") || strcmp(problemType, "cg"))
                strcpy(problemType, "Damage CPU");
                cout << "Enter the process [M] maintain [R] repair : ";
                cin >> process;
                switch (process)
                    case 'M':
                    case 'm': itemPrice = 124.00 ;
                    case 'R':
                    case 'r': itemPrice = 130.00 ;

        //output result//
        cout << "---------------------------OFFICIAL RECEIPT---------------------------" << endl;
        cout << "----------------------BRAINYTECH SERVICE CENTRE-----------------------" << endl;
        cout << "Name : " << cusName <<endl;
        cout << "Type Of Device : " << typeOfDev << endl;
        cout << "Problem Type : " << problemType << endl;
        cout << itemPrice << endl;

        return 0;

    • Slavic Sage

      When I tried running your code, when I get to the third input request (type of problem) it triggers some sort of error, which makes the code crash (I am running in Visual Studio 2017). But, in general, it considered good programming practice to use SOLID principles, especially SRP (Single Responsibility Principle). This means, that you should "evacuate" the part of your code where you ask for type of problem into a different function, outside of the main. You could even write a standalone code for that and test it, before importing it into this code. My guess would be there is some error with the type of problem. Sorry I can't be of more help. Good luck

  • Nahin

    >Otherwise, the else statement executes. That else statement is a nested if statement.

    Shouldn't it be 'That else statement is a nested if-ELSE statement.'?

  • btelfer

    I am wondering what is wrong with this code. it is supposed to take 3 numbers and 2 operators (of the same type) and give an answer.

    If I do:
    Enter a value: 7
    Enter an operator: *
    Enter a value: 7
    Enter an operator: *
    I get the answer:

    • nascardriver

      Your names are bad and you didn't enable compiler warnings are are ignoring them. Fix those and you'll see.
      See lesson 0.11, then rename your variables to names that make sense.

      • btelfer

        Thanks for the help. I didn't notice that I confused the compiler by telling it to send uninitialized values into "inputNum()" and "inputChar()". Additionally, I think "calculateAnswer(x, y, z, c, v);" does not work because I am putting values of two different types into an argument (int and char). I look forward to learning about union or templates to make this program work.

        • nascardriver

          You don't need unions or templates. `inputNum` and `inputChar` shouldn't have parameters. They should declare the variables locally.

          Your names caused you to mix up the argument order. This is what you're doing, but with more descriptive names

          Name variables descriptively, don't use abbreviations.

  • btelfer

    Here I have used "if" statements to make a very simple calculator:

    Is there a way to make this program reset automatically? Thanks!

  • Mike

    Hey nascardriver!
    Found inconsistencies in the code. First of all variable "x" hasn't been zero-initialized in any of the examples. And secondly, in the first snippet inside "common uses for if statements" newline feed is put inside double quotes instead of single quotes.

  • Ambareesh

    This happens because x = 0 first assigns 0 to x, then evaluates to the value 0, which is boolean false

    Why does it evaluate to 0? Is this like return 0 from main - denoting "successfully assigned value to variable"?

    • nascardriver

      Assignments return the variable that you're assigning to.

      Prints the new value of `x`, which is 123.

  • Noah

    Hello there,
    I was trying to create a small calculator, but I always get the result of my IF "Addieren" (adding).
    The User can decide between adding, subtracting, multiplying and dividing.
    Problem is, it doesn't matter what the user inputs, because the main always prints - if (1) (adding) or both of it and not the one, the user choose.

    I hope it's not to confusing and you guys could help me.
    Sorry for my language I'm from Germany.

    This is my main.cpp:

    my getCalcOperator.cpp:

    • nascardriver

      You got your if-statements wrong.
      main.cpp:22,28 are always true. The line 28 case will never be entered, because the line 22 condition was already true.

      In `getCalcOperator`, you're asking the user to enter a string, but you're extracting integers. In line 12 of getCalcOperator.cpp, you're extracting an integer. Then again in line 17. If the user entered 1 the second time, the condition in line 19 is `true` and the function returns 1. If the user entered 2 for the first integer, but not 1 for the second, the condition in line 26 is `true` and the function return 2. Otherwise, your function invokes undefined behavior, because you're not returning.

      If you want the user to enter a string, you need to extract into a string.

      You can then use an if-statement to check what the user entered

      To get a meaningful return value, you can add an enum

      and use that as the return type of `getCalcOperator`. The caller can then use another if-statement or switch-statement (Next lesson) to check the return type and call the according function.

      Please re-read this lesson, you seem to have misunderstood if-statement. If you have any questions, please ask.

  • salah

    What if I want to create a variable based on a condition
    for example :
                         int x;

    x won't be accessible outside of scope, how we can do such a thing ?

    • Alex

      If you want x to be accessible outside the scope of the if statement, then you need to define it before the if statement.

      • salah

        Thank you Alex, but I want to create X based on the condition,I mean if the condition inside if statement is true than create x and if false don't, at the same time I need x to be accessible in the main() scope .

        I want x to be accessible outside

        • Alex

          I think maybe you're actually trying to ask about dynamic memory allocation. This is covered in chapter P.

          You'd do something like this:

        • nascardriver

          If you want the variable to exist outside of the scope, you have to define it unconditionally. Then, in the conditional part, assign a value to `x`.

    • Salah

      Thank you so much I got the idea ❤

  • Jacob Salomon

    Hi nascardriver or Alex (HMMmm Has anyone ever seen you both together in the same room? :-))

    Anyway, I wanted to make sure I undestood you correctly in your "other example", where you have a long chain of if/else if:

    If I read correctly, these is a bunch of nested if's, as in:

    (Cue: Fake Russian accent) I find that verrry difficult to believe, Mr. Smart.  (Yeah, that reference definitely dates me!  :-)

    PLEASE tell me that's wrong!  I don't recall getting this kind of warning when I learned C language.


    • nascardriver

      Warning? That's just how it is, you don't have to think of it like that. There is no `else if` as such, it's just an `else` followed by another `if`. Right now, there's only one situation in which you have to remember this, `if constexpr`. `if constexpr` is an if-statement that is executed at compile-time, really useful when mixing types (Templates/auto is covered later).

  • Init-statements
    I use CodeBlock and the init statement doesn't compile.
    The error is:

    C:\CBPprojects\LearncppUnit5\main.cpp|42|error: expected ')' before ';' token|

    What might the problem?

  • omarbgm

    #include <iostream>

    using namespace std;

    namespace Animals
           enum Animals

    Hey im a newbie at c++ and iwas wondering why when i excute this code what ever the number i write i get the out pur of chicken only

  • sana ullah

    how to console 1 to 100   in if statement.
    and 1 to 100 negative.

  • Samira Ferdi

    Hi, Alex and Nascardriver!

    I found others code like this:

    I know how the code work, but what is your recommendation (because others do this)?

  • Parsa

    Visual Studio 2019 does not let me use an enum as a return type for a function(or at least I think that's what it's trying to tell me)

    What the error says: missing type specifier-int assumed. Note: C++ does not support default-int

    edit: I just realized I should have used a switch statement.

  • Samira Ferdi

    Hi, Alex and Nascardriver!

    I'm just curious about if-else statement and I just want to make sure my understanding about if-else.

    In the code above, if I entered 9, then the result is "19 has 2 digits". This is true because 19 has digits. I Agree with that. It's true that 19 is less than 100 but it is true also that 19 is less than 1000, and less than 10000. Why the result just is "19 has 2 digits"? I think the result should be:
    "19 has 2 digits"
    "19 has 3 digits"
    "19 has 4 digits"

  • Singh

    I am newbee to C++, can you help me to simplify below program. It do revolve the problem but code is quite lenthy which I think can be done in less code lines.

    • - Limit your lines to 80 characters in length for better readability on small displays.
      - Print the line feed at the end of the line, not at the beginning of the next line.
      - Inconsistent formatting. Use your editors auto-formatting feature.
      - Don't use "using namespace".
      - Use double literals for doubles.

      You can't reduce the line count, and doing so should not be a goal of yours. You could move the different fee calculations into functions, but they can't be merged, because they're too different from each other. Line (17), 18, 25, 26, 35, 36 should be moved outside of the conditional blocks.

      • Singh

        Thanks alot Alex, It will surely work as you have specified. Cheers!!

        • You're welcome! I'm not Alex though, Alex has a cat avatar and a blue message background :)

          • Singh

            I am really Sorry, I thought of you as Alex. I think I should correct it now "Thank you NascarDriver" ;). I will get back as soon as I got a query.

            Do you have Skype or anything other IM for direct communication as need some consultation regarding the carrier point of view. Thanks again, Cheers!!

  • Eric Mackay


    Is there a good way to take a number inputted by the user and look up a result based on the number that is not a whole bunch of if / if else statements?  As an example: in an RPG there might be a table listing numerous outcomes based on the random dice rolled by the player.  Is there a way to take that random number and search for the corresponding answer without coding something like this:

    I've been trying to code some useful tables for my gamer son using the above method and was thinking there's gotta be a better way.  Some tables are 3 items long, others are 200+.

    Any help would be appreciated.


    • Alex

      I can only think of 3 ways:
      1) Use a series of if/else
      2) Use a table to store the ranges and results and use a loop to do the iteration and comparison
      3) Use a table lookup where you initialize an array with your results and the use the userRoll as the array index.

      • Eric Mackay

        Thanks, Alex!

        I was afraid there was no simple solution.  I toyed with the idea of using a switch statement based on the dice roll.  This might work for a situation where there is one result per number on the dice, but in my example above it would be silly and more cumbersome to use...

        Thanks again for the ideas!


  • Matt

    Hi Alex!

    I've been away for a while and am currently doing review of old lessons.

    My question is about style/technique here, in the following code:

    Since enum class is used instead of a standard enum, isn't it unnecessary to disambiguate the members with ERROR_... considering accessing them already requires using the ErrorCode:: prefix?


  • Hi Alex!

    This lesson is missing the optional init-statement

  • Nguyen

    Hi nascardriver,

    I need your help.  Is there any Date type? I just came up with a simple and small program.  
    Here is my example:  if the due date is before 10/25/2018, then you will not be fined.  If the due date is between 10/26/2018 and 11/26/2018, then you will be fined $100.  If the due date is after 11/26/2018, then you will be fined $200.

    Here is my pseudocode:

    Could you please help me to code my example?
    I'd like to know if I set the conditions correctly.

    Thanks, Have a great day.

    • Alex is the C++ way of handling time and dates. Personally I haven't had the chance to use the date functionality here, but it would make a good future lesson. I'll add it to my to-do list.

    • Hi Nguyen!

      As Alex said, @std::chrono is the way to go. Date and Time are terrible to work with, because there's no real logic behind. A minute is 60 seconds, a day is 24 hours, a month is 28-31 depending on the year and so on. If you can't solve it with @std::chrono, your best bet is to convert everything to seconds and go from there.

  • Juan

    How can I initialise a constant inside an if statement? Something like

    I either initialise it outside the if and it cannot be const, or I initialise it inside and I cannot use it outside the if.


    • Hi Juan!

      Lesson 3.4 - Sizeof, comma, and conditional operators

      • Juan

        ok, great, I was hoping I could avoid conditional operators, but I'll have to settle for one of my options. Thanks!

        • You could also create a non-const variable first, assign the value with a normal if-statement and initialize a const with that variable. I can't think of a reason why you would need a const variable though.

  • Benjamin

    In this example below you have:

    Shouldn't that be "exclusive" not "inclusive"?


    should say "is 10 or less"

  • Bud Roszales

    This website is completely gret. I've researched these details a great deal and
    I view it that is good written, fast to comprehend.
    I congratulate you because of this research that I am going to recommend to the people around.
    I ask you to recommend the site where each university student or
    learner can find results grade point average rating.

    Thank you!

  • Ali Dahud

    Could anyone please explain me this code?
    in Detai please

    • nascardriver

      Hi Ali!

      If you want a detailed description you should provide full code.

  • Peter Baum

    Under chaining if statements -   I felt confused encountering “else if” because it wasn’t really explained in detail.  When I saw the second “else” in the example, I didn’t know if the “else” functioned relative to the “else if” or the “if” at the top.

    Perhaps just adding a little more detail to this section will help.

  • Andrew

    What is the goal of using ''null statement''?

    • Alex

      Null statements are typically used when the language requires a statement to exist but the programmer doesn't need one. Most often, this occurs in conjunction with loops, where the termination condition of the loop is performing all of the evaluation necessary.

      For example:

      This code will continue to execute playGame() as long as playGame() returns boolean true.

      • Peter Baum

        I would like to see this moved into the lesson.  Could you also provide another example?  Personally I learn better when I am shown how I might use something rather than trying to retain it in my memory for some unknown purpose in the future.

        • Alex

          I updated the text a bit -- the challenge here is that null statements are almost never used with if statements, so any example would be equally contrived. This is here more to serve as a warning of what to watch out for, than to be something I expect you to use yet.

          Thanks for the feedback.


    Is it possible for us to create square root function by ourselves with the knowledge we had up to this point?

  • April

    I'm still having a hard time understanding the benefit of using enumerated value error codes. Would you mind elaborating, please?

  • Kushagra

    In most of the cases return value of int main()
    is 0. Then why don't we use void main() instead of int main()?  Please explain.

  • Gurdeep Singh

    Just asking out of curiosity

    Are there any plans to make tutorials for other programming languages.

Leave a Comment

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