/* ** $Id: args.c 802 2008-03-01 19:26:43Z phf $ ** ** Handling variable-length parameter lists, aka "How to ** implement printf() if you really really need to." No ** time for comments right now, enjoy reading the code. */ #include #include #include #include #include int add(int howmany, ...) // and whatever follows { va_list ap; va_start(ap, howmany); int sum = 0; for (int i = 0; i < howmany; i++) { int x = va_arg(ap, int); sum += x; } va_end(ap); return sum; } int main() { printf("Great: %d\n", add(5, 1, 2, 3, 1, 1)); printf("Hmmm: %d\n", add(3, 1, 2, 3, 1, 1)); printf("Oops: %d\n", add(7, 1, 2, 3, 1, 1)); return EXIT_SUCCESS; }