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
CodePudding user response:
The variadic function needs some way of knowing how many values you have passed to the function. Therefore, you should additionally pass this number as the first argument to the function:
#include <stdio.h>
#include <stdarg.h>
int add( int num_values, ... )
{
va_list add_list;
va_start( add_list, num_values );
int sum = 0;
for ( int i = 0; i < num_values; i )
sum = va_arg( add_list, int );
va_end(add_list);
return sum;
}
int main( void )
{
int result = add( 5, 5, 6, 7, 8, 9 );
printf( "%d\n", result );
return 0;
}
This program has the following output:
35
CodePudding user response:
You say that you have y
optional arguments, but actually you have only 3, instead of 6.
int result = add(5, 3, 7, 8, 9);
should work.
PS: Also, you do not use the first parameter x
, so you can remove it.