Skip to content

Instantly share code, notes, and snippets.

@StrikeW
Created April 21, 2014 10:03
Show Gist options
  • Save StrikeW/11138197 to your computer and use it in GitHub Desktop.
Save StrikeW/11138197 to your computer and use it in GitHub Desktop.
C varargs: variable-length argument list
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
double average(int i, ...);
int main(int argc, char *argv[])
{
double x = 22.5, y = 10.5, z = 13.2;
printf("x+y+z=%.2f\n", average(3, x, y, z));
printf("x+y=%.2f\n", average(2, x, y));
return 0;
}
/**
* @param i num of values to be averaged
*/
double average(int i, ...)
{
double total = 0;
va_list args;
va_start(args, i); /* i is the rightmost arg before '...' */
for (int j = 1; j <= i; ++j) {
total += va_arg(args, double); // fetch next arg
}
va_end(args); /* clean up arg-list */
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment