Variadic Function in C

Level 5267 keystrokes

Defines a variadic function sum whose first argument says how many ints follow, and reads them with the stdarg.h macros va_start, va_arg and va_end. sum(3, 10, 20, 30) gives 60 and sum(5, 1, 2, 3, 4, 5) gives 15.

C code

// ... accepts any number of extra arguments; count tells the function how many to read
1int sum(int count, ...) {
// Holds the position in the variable argument list
2 va_list args;
// Starts reading right after the last named parameter, count
3 va_start(args, count);
// Running total
4 int total = 0;
// Reads exactly count arguments
5 for (int i = 0; i < count; i++) {
// va_arg returns the next argument as an int and advances the list
6 total += va_arg(args, int);
7 }
// Every va_start needs a matching va_end
8 va_end(args);
// Returns the sum
9 return total;
10}
11
// 3 values follow: 10 + 20 + 30 prints Sum of 3: 60
12printf("Sum of 3: %d\n", sum(3, 10, 20, 30));
// 5 values follow: 1 + 2 + 3 + 4 + 5 prints Sum of 5: 15
13printf("Sum of 5: %d\n", sum(5, 1, 2, 3, 4, 5));

Output

Sum of 3: 60
Sum of 5: 15
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ,× 13
  • ;× 10
  • (× 9
  • )× 9
  • _× 4
  • "× 4
  • .× 3
  • +× 3
  • =× 3
  • :× 2

More C examples at level 5

← C typing practice