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 read1int sum(int count, ...) { // Holds the position in the variable argument list2 va_list args; // Starts reading right after the last named parameter, count3 va_start(args, count); // Running total4 int total = 0; // Reads exactly count arguments5 for (int i = 0; i < count; i++) { // va_arg returns the next argument as an int and advances the list6 total += va_arg(args, int);7 } // Every va_start needs a matching va_end8 va_end(args); // Returns the sum9 return total;10}11 // 3 values follow: 10 + 20 + 30 prints Sum of 3: 6012printf("Sum of 3: %d\n", sum(3, 10, 20, 30));// 5 values follow: 1 + 2 + 3 + 4 + 5 prints Sum of 5: 1513printf("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. 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