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

154 comments to 5.2 — If statements

  • yeokaiwei

    In the previous chapter S4.5-Enumerated Types

    "Best practice

    Don’t assign specific values to your enumerators."

    It's confusing.

    Which rule do we follow?

    • TigerTM

      Like pretty much all programming. It depends. As a general rule you shouldnt assign specific values, but there are some cases where it makes sense. When in doubt follow generalized rules unless you have a good reason not to.

      Using an enum class in this case makes sense, it keeps things together all in one place, but an equally valid solution would have been to store them as constants in a namespace. This is just less work and serves the purpose of the example well.

      Chosing to store it as an enum instead of a constant means that it can be passed as a variable instead of just an int value, which can be really helpful sometimes. You inherently get more information with an enum variable than you do with just an int.

    • nascardriver

      No specific values should have been assigned in this example, I've updated the lesson. Thanks for pointing it out!
      What you quoted is a "Best practice", and that's also what @TigerTM described. Follow the "Best practice" unless you have a good reason not to. For specific enumerator values, a good reason to diverge from the best practice can be that the values must not change during updates or that the values are exposed to the user. Both these scenarios can be met with error code enums. If error code 42 meant "file not found" in program version 1.2.1, it should still have the same meaning in version 1.3.4. By assigning specific values, you're preventing the programmer from inserting an enumerator between others, thus shifting all values.
      Since the enumerator values aren't exposed in this example, there's no need for specific values to be used.

  • allright

    it allows multiple init statements of same type but not different types or am i missing a point here

  • Andreas Krug

    Shouldn't the first line of the "Using logical operators with if statements" chapter end with "(covered in section 5.7 -- Logical operators)" instead of "(covered in section 3.6 -- logical operators)"?

Leave a Comment

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