Control flow

If statement

if statement

  • Syntax:

    if (condition) {
        // do something
    }
  • Condition:

    • A boolean expression that evaluates to true or false.
    • Any non-zero value is considered true, and zero is considered false.
  • If the condition is true, the code block inside the if statement will be executed.

  • If the condition is false, the code block inside the if statement will be skipped.

Examples

int a = 10;
if (a > 0) {
    cout << "a is positive" << endl;
}

If the statement takes only one line, you can use the following syntax:

if (a > 0) 
    cout << "a is positive" << endl;
cout << "This line is always executed";

Condition can be any expression.

float b = 0.5;
if (b) { // not recommended, make the code less readable
    cout << "b is true" << endl;
}

if-else statement

  • Syntax:

    if (condition) {
        // do something
    } else {
        // do something else
    }
  • It will execute the code block inside the if statement if the condition is true.

  • It will execute the code block inside the else statement if the condition is false.

int a = -10;
if (a > 0) {
    cout << "a is positive" << endl;
} else {
    cout << "a is negative" << endl;
}

If there’s only one statement, you can use the following syntax:

if (condition) statement1;
else statement2;


To make the code more readable, avoid using ambiguous sytntax.

For example, when will “Where I’m?” be printed?

if (num < 10)
if (num < 5)
    cout << "The number is less than 5" << endl;
else
    cout << "Where I'm?" << endl;

else-if statement

  • Syntax:

    if (condition1) {
        // do something
    } else if (condition2) {
        // do something else
    } else {
        // do something else
    }
  • It will execute the code block inside the if statement if the condition1 is true.

  • It will execute the code block inside the else if statement if the condition2 is true.

  • It will execute the code block inside the else statement if the condition1 and condition2 are false.

?: operator (ternary operator)

  • Syntax:

    condition ? expression1 : expression2;
  • It will return expression1 if the condition is true.

  • It will return expression2 if the condition is false.

When to use ?: operator?

  • When you want to assign a value to a variable based on a condition.
  • When you want to return a value from a function based on a condition.
int a = 10;
int b = 20;
int c = a > b ? a : b; // c = 20

Comparison operators

  • ==: equal to
  • !=: not equal to
  • <: less than
  • >: greater than
  • <=: less than or equal to
  • >=: greater than or equal to

These operators return true if the condition is true, otherwise false.

Logical operators

  • &&: and, returns true if both operands are true.
  • ||: or, returns true if either operand is true.
  • !: not, returns true if the operand is false.
  • ^: xor, returns true if both operands are different.

Precedence of logical operators: ! > && > ||.

int a = 10;
int b = 20;
int c = 30;
// the next line is equivalent to (a > 0 && b > 0) || c > 0
if (a > 0 && b > 0 || c > 0) {
    cout << "a, b are positive or c is positive" << endl;
}

Statement scope

Statement scope is the scope of a statement. Usually scope is defined by {}.

  • A variable defined outside a statement scope can be used in the statement scope and its nested statement scopes.
  • A variable defined in a statement scope cannot be used in the parent statement scope.
int a = 10;
if (a > 0) {
    int b = 20;
    a = 100;
    cout << "b = " << b << endl;
}
cout << "a = " << a << endl; // a = 100
cout << "b = " << b << endl; // error: b is not defined

Switch statement

  • Syntax:

    switch (expression) {
        case constant1:
            // do something
            break; // don't forget this!
        case constant2:
            // do something
            break; // don't forget this!
        default:
            // do something
            break; // don't forget this!
    }
  • The code block executes when the value of the expression matches the constant in the case.

  • The break statement is used to terminate the switch statement.

    • If you don’t use break, the code block inside the case will be executed sequentially.
  • The default statement is executed if none of the cases are matched.

Iterations

while loop

  • Syntax:

    while (condition) {
        // do something
    }
  • It will execute the code block inside the while loop as long as the condition is true.

  • The condition is evaluated before the code block inside the while loop is executed.

int i = 0;

while (i < 10) {
    cout << "i = " << i << endl;
    i++;
} // 10 will not be printed

do-while loop

  • Syntax:

    do {
        // do something
    } while (condition);
  • It will execute the code block inside the do-while loop at least once.

  • The condition is evaluated after the code block inside the do-while loop is executed.

int i = 0;

do {
    cout << "i = " << i << endl;
    i++;
} while (i < 10); // 10 will be printed

For loop

  • Syntax:

    for (initialization; condition; increment) {
        // do something
    }
  • The variable defined in the initialization part is only visible in the for loop.

Example:

int sum = 0;

for (int i = 0; i < 10; i++) {
    sum += i;
}

cout << "sum = " << sum << endl; // ok, sum is defined outside the loop
cout << "i = " << i << endl; // error: i is not defined

The increment part of the for loop can be omitted.

int sum = 0;

for (int i = 0; i < 10; ) {
    sum += i;
    i++;
}

The initialization part of the for loop can be omitted. In this case, i can be used after the loop.

int sum = 0;
int i = 0;

for (; i < 10; i++) {
    sum += i;
}

The increment part of the for loop can be other expressions.

int sum = 0;

for (int i = 0; i < 10; i += 2) {
    sum += i; // sum the even numbers from 0 to 9
}

for loop vs while loop

The two loops are equivalent, except the scope of the variable i.

int i = 0;
while (i < 10) {
    cout << "i = " << i << endl;
    i++;
} // i can be used after the loop
for (int i = 0; i < 10; i++) {
    cout << "i = " << i << endl;
} // i can't be used after the loop

Endless loop

Sometimes we want to create a loop that will run forever. For example, we want to create a game that will run until the player wins.

while (true) {
    // game logic
}


for (;;) {
    // game logic
}

Sometimes your program runs in by mistake, be careful.

// mistake 1: size_t is unsigned, so it will not be less than 0
size_t i = 10;
while (i > 0) {
    cout << "i = " << i << endl;
    i--;
}

// mistake 2: the condition is an assignment to flag, it will always be true
bool flag = true;
int count = 0;
// mistake: flag = true is an assignment, not a comparison
while (flag = true) {
    count++;
    if (count == 5) {
        flag = false;
    }
}

Value of expression

Each expression in C++ has a value,

  • 3+4 has the value 7.
  • a > b has the value true or false.
  • a+b has the value of a+b.
  • a = b has the value of b.

The assignment operator = has the lowest precedence, so a = b = c is equivalent to a = (b = c). see cppreference.

// example used to show the value of expression
// not recommended to use this way
int a = 10;
int b = 20;
int c = a = b; // c = 20, a = 20, b = 20
// equivalent to int c = (a = b);

Jump statements

break statement

The break statement is used to terminate the loop or switch statement.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    cout << "i = " << i << endl;
}
// outputs: 0 1 2 3 4
int i = 0;
while (true) {
    if (i == 5) {
        break;
    }
    cout << "i = " << i << endl;
    i++;
}
// outputs: 0 1 2 3 4

continue statement

The continue statement is used to skip the rest of the code block inside the loop and continue the loop.

  • In while or do-while loop, the next iteration starts after the condition is evaluated.
  • In for loop, the increment part is executed first, then the condition is evaluated.
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue;
    }
    cout << "i = " << i << endl;
}
// 6 is output directly because the continue statement is executed when i == 5.
// outputs: 0 1 2 3 4 6 7 8 9

Example:

int i = 0;
while (i < 10) {
    if (i == 5) {
        continue;
    }
    cout << "i = " << i << endl;
    i++;
}
// outputs: 0 1 2 3 4 then endless loop
int i = 0;
while (i < 10) {
    cout << "i = " << i << endl;
    i++;
    if (i == 5) {
        continue;
    }
}
// outputs: 0 1 2 3 4 6 7 8 9

References