I was testing variadic functions in C. The following was supposed to return the sum of all of the arguments but it keeps printing garbage values instead.
#include <stdio.h>
#include <stdarg.h>
int add(int x, int y, ...)
{
va_list add_list;
va_start(add_list, y);
int sum = 0;
for (int i = 0; i < y; i++)
sum += va_arg(add_list, int);
va_end(add_list);
return sum;
}
int main()
{
int result = add(5, 6, 7, 8, 9);
printf("%d\n", result);
return 0;
}
I thought it was going to return the sum of all of the arguments
addimplementation is using the second parameter as a count of the remaining number of args. So your calladd(5, 6, 7, 8, 9)is invalid (unless I've misunderstood).