10. If Statements

The purpose of an if statement is to enable a program to decide which statements to execute. The primary difference between an if statement and a switch, discussed in the next section, is an if statement allows for actions based upon a range of values of various data types while a switch makes decisions solely on a limited set of integer values.

General Form

The general form of an if statement is as follows:

if (test) {
    true-part
} else {
    false-part
}

Some important points:

If no action needs to be taken when the test evaluates to false, the “false” part of the if statement should be omitted.

Do not put a semicolon after the closing parenthesis at the top of the if statement. If a semicolon is placed there accidentally, the if statement will not work correctly.

The statements in the “true” and “false” parts of an if statement should be indented and left aligned to visually emphasize they are in the if statement.

How an If Statement Works

The steps taken when an if statement executes are as follows:

  1. The test is performed.
  2. If the test evaluates to true, the statements in the “true” part are executed then execution passes to the first executable statement after the if statement.
  3. If the test evaluates to false, the statements in the “false” part are executed then execution passes to the first executable statement after the if statement.

The keywords if and else do not perform any action. They only indicate the beginning of an if statement’s two sections.

Example – “True” and “False” Parts

The example that follows shows an if statement with both “true” and “false” parts. The user is asked to enter a number and the if statement is used to determine whether the number is valid. Step through the code following the steps above. Note that a range of values is checked for in the test:

int number;

std::cout << "Enter a number between 5 and 12, inclusive: ";
std::cin >> number;

if (number < 5 || number > 12) {
    std::cout << "Your number is invalid" << std::endl;
} else {
    std::cout << "Nice number " << std::endl;
}

Example – “True” Part Only

Sometimes a program will not need to decide between statements to execute but instead need to determine whether a statement should be executed. The example that follows shows an if statement without a “false” part. If the price is valid, the calculation will take place, otherwise no action will be taken:

if (price > 0) {
    total = price + taxes;
}

The braces are included in this example. It would also be ok to omit them. In both cases, the actions taken are exactly the same.

Example – Nested If Statements

A program may need to decide between more than two options. Nested if statements are used in this case. Tests are evaluated until one evaluates to true and then the statements in that section of the if statements are executed. If all tests evaluate to false and an else section ends the statements, the code in this section will be executed.

What follows are two versions of the same code. The only difference between the examples is the formatting of the nested if statements. In the first version, each nested if statement is visually placed within an outer if statement. In the second, the nested if statements are organized into an else if format. Either approach is fine. Step through both examples to verify they work the same. Note that a single value is checked for in each test. Also, the braces could be removed from both examples.

// First version

int choice;

std::cout << "Your choice (1, 2, or 3): ";
std::cin >> choice;

if (choice == 1) {
    std::cout << "This is the best choice!" << std::endl;
} else {
    if (choice == 2) {
        std::cout << "This is the second best choice!"
                  << std::endl;
    } else {
        if (choice == 3) {
            std::cout << "Oh well..." << std::endl;
        } else {
            std::cout << "Oops!!!" << std::endl;
        }
    }
}
// Second version

int choice;

std::cout << "Your choice (1, 2, or 3): ";
std::cin >> choice;

if (choice == 1) {
    std::cout << "This is the best choice!" << std::endl;
} else if (choice == 2) {
    std::cout << "This is the second best choice!" << std::endl;
} else if (choice == 3) {
    std::cout << "Oh well..." << std::endl;
} else {
    std::cout << "Oops!!!" << std::endl;
}