Variadic Functions in Cilk

Here’s a function that will take an arbitrary number of ints as arguments.

#include <stdio.h>

void sum(int count, ...) {
    va_list nums;
    va_start(nums, count);
    printf("[");
    int total = 0;
    for (int i = 0; i < count; ++i) {
        int num = va_arg(nums, int);
        total += num;
        printf(" %d", num);
    }
    printf(" ] %d\n", total);
    va_end(nums);
}

int main() {
    sum(2, 1, 2);
    sum(3, 1, 2, 3);

    int nums[] = {1, 2, 3, 4};
    sum(4, nums[0], nums[1], nums[2], nums[3]);

    return 0;
}

To run the program, compile the code using a C compiler and execute the resulting binary.

$ gcc variadic-functions.c -o variadic-functions
$ ./variadic-functions
[ 1 2 ] 3
[ 1 2 3 ] 6
[ 1 2 3 4 ] 10

In this example, we use the stdarg library to handle variadic arguments. The sum function first initializes a va_list and iterates over each integer argument to compute the total sum, printing the results along the way. The main function demonstrates calling the variadic sum function with different numbers of arguments.

Next, we’ll look at another key aspect of functions in Cilk, closures.