Search

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

or

if (expression)
    statement
else
    statement2

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)
    statement
else
    statement2

is actually the equivalent of:

if (expression)
{
    statement
}
else
{
    statement2
}

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:

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.

While null statements are rarely used in conjunction with if statements intentionally, they sometimes unintentionally cause problems. 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.

5.3 -- Switch statements
Index
5.1 -- Control flow introduction

51 comments to 5.2 — If statements

  • 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 fight.the.purple@hotmail.co.uk 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 😀 ? 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.

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

  • 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…
    MANY GOOD JOBS…

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

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

  • sethradio

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

  • ericofilho

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

    if (pnPtr)
    cout << "pnPtr is pointing to an integer.";
    else
    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:

  • 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
    #include // for sqrt()

    void PrintSqrt(double dValue)
    {
    using namespace std;
    if (dValue >= 0.0)
    cout << "The square root of " << dValue << " is " << sqrt(dValue) << endl;
    else
    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.
      Ex:
      #include
      int main()
      {
      double myValue = 2.0;
      PrintSqrt(myValue);
      return 0;
      }

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

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

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

    Thanx
    -Kanchana

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

  • sara

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

  • Te KA

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

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

  • Sourav jadhav

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

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

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

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

  • 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

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

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

  • Andrew

    Hello!
    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.

Leave a Comment

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