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

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

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 a nested 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.

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

93 comments to 5.2 — If statements

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

    Thanks

    • Hi Juan!

      References
      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"?

    Also

    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 gpa-calculator.co 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.

  • IMRAN ALI

    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]