5.11. Functions with Variable-Length Argument Lists

[ fromfile: ellipsis.xml id: ellipsis ]

Example 5.20. src/ellipsis/ellipsis.cpp

#include <cstdarg>
#include <iostream>
using namespace std;

double mean(int n ...) {    1
    va_list ap;             2
    double sum(0);
    int count(n);
    va_start(ap, n);        3
    for (int i = 0; i < count; ++i) {
        sum += va_arg(ap, double);
    }
    va_end(ap);             4
    return sum / count;
}

int main() {
    cout << mean(4, 11.3, 22.5, 33.7, 44.9) << endl;
    cout << mean (5, 13.4, 22.5, 123.45, 421.33, 2525.353) << endl;
}

1

First parameter is number of args.

2

Sequentially points to each unnamed arg.

3

Now, ap points to first unnamed arg.

4

Clean up before returning.