If Else in Cilk

Branching with if and else in Cilk is straightforward.

#include <cilk/cilk.h>
#include <iostream>

int main() {
    // Here's a basic example.
    if (7 % 2 == 0) {
        std::cout << "7 is even" << std::endl;
    } else {
        std::cout << "7 is odd" << std::endl;
    }

    // You can have an `if` statement without an else.
    if (8 % 4 == 0) {
        std::cout << "8 is divisible by 4" << std::endl;
    }

    // Logical operators like `&&` and `||` are often
    // useful in conditions.
    if (8 % 2 == 0 || 7 % 2 == 0) {
        std::cout << "either 8 or 7 are even" << std::endl;
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    int num = 9;
    if (num < 0) {
        std::cout << num << " is negative" << std::endl;
    } else if (num < 10) {
        std::cout << num << " has 1 digit" << std::endl;
    } else {
        std::cout << num << " has multiple digits" << std::endl;
    }

    return 0;
}

To compile and run the Cilk program:

$ clang++ -fcilkplus if-else.cpp -o if-else
$ ./if-else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that you need parentheses around conditions in Cilk, and the braces are required for multi-line blocks.

Cilk, being an extension of C++, supports the ternary operator ?:, which can be used for simple conditional expressions. However, for clarity and consistency with the original example, we’ve used full if statements.