1

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

1
  • 3
    You're add implementation is using the second parameter as a count of the remaining number of args. So your call add(5, 6, 7, 8, 9) is invalid (unless I've misunderstood). Commented Dec 14, 2022 at 17:08

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments