I'm studying the C programming language and one thing I found very interesting is the implementation of a variadic function. I'm currently trying to print each value passed into the function, but I'm only getting a part of the arguments.
I tried running some examples I found online for average number from parameters and also a sum algorithm (shown below).
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...)
{
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++) {
int num = va_arg(args, int);
total += num;
printf("Value #%d: %d\n", i, num);
}
va_end(args);
return total;
}
int main()
{
int result = sum(1, 2, 3, 4, 5);
printf("The result is: %d\n", result);
}
The code above only prints:
Value #0: 2
The result is: 2
I think it's because the for loop is using the first argument as the max value of the index. But...
My question here is how printf works if it's not necessary to pass the amount of arguments to replace within the formatted string?
Is it because behind the scenes, the C runtime counts how many format specifiers are declared in the formatted string? That's my guess.