Namespaces
Variants
Views
Actions

The if statement

From cppreference.com


The if statement evaluates a condition and depending on the outcome, either executes a set of statements, or not.

It looks like this:

if (/* test */) {
    // statements
}

And works like this:

  1. Run the expression /* test */, which should return true or false.
    1. If the result is true, run the statements in the block.
    2. If the result is false, skip past the block without running the statements.

For example:

if (x == 2) {
    y = 4;
}

Does:

  1. Run the expression x == 2, which will return true if x is equal to 2, and false otherwise.
    1. If the result is true (ie, x is equal to 2), run the statements in the block. So the statement y = 4 is executed.
    2. If the result is false (ie, x is not equal to 2), skip past the block without running the statement.

[edit] The if-else statement

There exists a form of an if statement that executes another set of statements if the condition evaluates to false.

It looks like this:

if (/* test */) {
    // first block
}
else {
    //second block
}

And works like this:

  1. Run the expression /* test */, which should return true or false.
    1. If the result is true, run the statements in the first block.
    2. If the result is false, run the statements in the second block.

For example, in the following example, z is assigned 6 only if x is not equal to 2.

if (x == 2) {
    y = 4;
} else {
    z = 6;
}

The runnable example below illustrates the if statement:

#include <iostream>
 
int main()
{
    int x = 2; // change this and see the results
    if (x == 2) {
        std::cout << "x is equal to 2\n";
    }
 
    int y = 17;
    if (x == 3) {
        y = 4;
    }
    std::cout << "y: " << y << "\n";
 
    if (y == 17) {
        std::cout << "y is equal to 17\n";
    } else {
        std::cout << "y is not equal to 17\n";
    }
}

Output:

x is equal to 2
y: 17
y is equal to 17