1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdarg.h>  // va_list, va_start(…), va_arg(…), va_end(…)
// Must include stdarg.h for variadic function
// Variadic function must take at least one parameter

// VARIADIC FUNCTION to add an arbitary number of numbers.

int sum(int n_first, ...) { // ... means and 0 or more parameters.
         // ↑
         // last named parameter is n_first
    va_list more_args;  // more_args is a name that you can choose.
    va_start(more_args, n_first);  // va_start(«va_list object», «last named parameter»);
    int arg = n_first;
    while(arg != 0) {
        arg = va_arg(more_args, int);
        // va_arg(«va_list object», «expected arg type»).

        sum += arg;
    }
    va_end(more_args);  // clean up (to avoid memory leaks, etc.). (penalty if you forget)
    return n_first + n_next;
}

int main(int argc, char* argv[]) {
    printf("sum(0) == %d\n", sum(0)); //////////////////// Step 1 (TDD)
    printf("sum(5, 0) == %d\n", sum(5, 0)); ////////////// Step 2
    printf("sum(5, 7, 0) == %d\n", sum(5, 7, 0)); //////// Step 3
    printf("sum(3, 5, 7, 0) == %d\n", sum(3, 5, 7, 0)); // Step 4
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.