Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variadic function returns garbage value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading