Functions in Cilk

Functions are central in Cilk. We’ll learn about functions with a few different examples.

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

// Here's a function that takes two ints and returns
// their sum as an int.
int plus(int a, int b) {
    // Cilk, like C++, automatically returns the value of the last
    // expression in a function if it matches the return type.
    return a + b;
}

// In Cilk, we can use the same syntax as C++ for function declarations.
// When you have multiple consecutive parameters of the same type, 
// you can declare them together.
int plusPlus(int a, int b, int c) {
    return a + b + c;
}

int main() {
    // Call a function just as you'd expect, with name(args).
    int res = plus(1, 2);
    std::cout << "1+2 = " << res << std::endl;

    res = plusPlus(1, 2, 3);
    std::cout << "1+2+3 = " << res << std::endl;

    return 0;
}

To compile and run the Cilk program:

$ cilk++ functions.cilk -o functions
$ ./functions
1+2 = 3
1+2+3 = 6

Cilk extends C++ with support for parallel programming, but for these simple functions, the syntax is very similar to standard C++. The main differences in Cilk typically come into play when dealing with parallel constructs, which we haven’t used in this basic example.

There are several other features to Cilk functions, particularly related to parallelism. One of the key features is the ability to spawn parallel tasks, which we’ll look at in later examples.