Variable Function Parameters
With C++ there is ways of handling optional function parameters or overloading functions to handle different amounts of parameters, obviously within C these abilities do not exist. However if we wanted to handle a variable list of parameters then C and C++ would work the same.
Let’s see how we’d do that:
#include <stdarg.h> #include <stdio.h> int Adding(int cnt, ...) { /* the three ... indicate a variable list */ int add, tmp, i; va_list args; /* make a va_list */ va_start(args, cnt); /* variable list starts after 'cnt' */ for(i = 0; i < cnt; i++) { tmp = va_arg(args, int); /* grab the next */ add = add + tmp; /* add to the sum */ } va_end(args); /* finished using variable list */ return add; } int main( ) { int a; a = Adding(2, 1, 2); printf("%u\n", a); /* Outputs 3 */ a = Adding(3, 1, 2, 3); printf("%u\n", a); /* Outputs 6 */ return 0; }
So the first argument indicates how many variables we are going to pass and the rest are summed together. The function Adding() would be identical in C++.