Statements and Control Flow

Selection: if / else

  • Syntax:

    if (condition) statement 
    
    if (condition) statement1 else statement2
    
  • Example:

    if (x > 0)
        cout << "x is positive";
    else if (x < 0)
        cout << "x is negative";
    else
        cout << "x is 0";
    

Selection: switch

  • Syntax:

    switch (expression) {
        case constant1:
            group-of-statements-1;
            break;
        case constant2:
            group-of-statements-2;
            break;
        .
        .
        .
        default:
            default-group-of-statements
    }
    
    • The switch statement has a somewhat peculiar syntax inherited from the early times of the first C compilers, because it uses labels instead of blocks.

  • switch  evaluates expression and checks if it is equivalent to constant1; if it is, it executes group-of-statements-1 until it finds the break statement. When it finds this break  statement, the program jumps to the end of the entire switch  statement (the closing brace).

  • Its purpose is to check for a value among a number of possible constant expressions. It is something similar to concatenating if-else statements, but limited to constant expressions.

  • switch  is limited to compare its evaluated expression against labels that are constant expressions. It is not possible to use variables as labels or ranges, because they are not valid C++ constant expressions.

    • To check for ranges or values that are not constant, it is better to use concatenations of if  and else if  statements.

Iteration: For Loop

  • Syntax:

    for (initialization; condition; increase) statement;
    
  • Example:

    #include <iostream>
    
    int main () {
        for (int n=10; n>0; n--) {
            std::cout << n << ", ";
        }
        std::cout << "liftoff!\n";
    }
    
Handling many counter variables
  • 'initialization', 'condition', and 'statement' are expressions, and so they can make use of the comma operator (,):

for ( n=0, i=100 ; n!=i ; ++n, --i ) {
   
}

Iteration: Range-based For Loop

  • Syntax:

    for ( declaration : range ) statement;
    
  • This kind of for loop iterates over all the elements in range, where declaration declares some variable able to take the value of an element in this range. Ranges are sequences of elements, including arrays, containers, and any other type supporting the functions begin  and end .

  • Example:

    #include <iostream>
    #include <string>
    
    int main ()
    {
        std::string str {"Hello!"};
        for (char c : str){
            std::cout << "[" << c << "]";
        }
        std::cout << '\n';
    }
    

Iteration: While Loop

  • Syntax:

    while (expression) statement
    
  • Example:

    #include <iostream>
    
    int main () {
        int n = 10;
    
        while (n > 0) {
            std::cout << n << ", ";
            --n;
        }
    
        std::cout << "liftoff!\n";
    }
    

Iteration: Do-While Loop

  • Syntax:

    do statement while (condition);
    
  • It behaves like a while-loop, except that condition is evaluated after the execution of statement instead of before, guaranteeing at least one execution of statement, even if condition is never fulfilled.

  • Example:

    • The program echoes any text the user introduces until the user enters goodbye.

    #include <iostream>
    #include <string>
    
    int main () {
        std::string str;
        do {
            std::cout << "Enter text: ";
            std::getline(std::cin, str);
            std::cout << "You entered: " << str << '\n';
        } while (str != "goodbye");
    }
    

Jump: break

  • It leaves a loop, even if the condition for its end is not fulfilled.

  • It can be used to end an infinite loop, or to force it to end before its natural end.

#include <iostream>

int main () {
    for (int n=10; n>0; n--) {
        std::cout << n << ", ";
        if (n==3) {
            std::cout << "countdown aborted!";
            break;
        }
    }
}

Jump: continue

  • It causes the program to skip the rest of the loop in the current iteration, as if the end of the statement block had been reached, causing it to jump to the start of the following iteration.

int main () {
    for (int n=10; n>0; n--) {
        if (n==5) continue;
        std::cout << n << ", ";
    }
    std::cout << "liftoff!\n";
}

Jump: goto

  • It allows to make an absolute jump to another point in the program. This unconditional jump ignores nesting levels, and does not cause any automatic stack unwinding. Therefore, it is a feature to use with care, and preferably within the same block of statements, especially in the presence of local variables.

  • The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).

#include <iostream>

int main () {
    int n=10;
my_label:
    std::cout << n << ", ";
    n--;
    if (n>0) goto my_label;
    std::cout << "liftoff!\n";
}