-1

Consider:

#include<stdio.h>
#include<stdarg.h>

int sum(int, ...);

int main(void)
{
    int answer = sum(4, 4, 3, 2, 1);
    printf("합은 %d입니다.\n", answer);

    return 0;
}

int sum(int num, ...)
{
    int answer = 0;
    va_list argptr;

    va_start(argptr, num);
    for (; num > 0; num--)
        answer += va_arg(argptr, int);

    va_end(argptr);
    return(answer);
}

This is a variable parameter function.

What is the "stdarg.h"? I couldn't find it in my book about va_list, va_end, and va_start.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

1

The header "stdarg.h" is a standard C header which declares some macros useful for dealing with the functions with varying number of arguments of varying types. The most important macros declared are va_list, va_start, va_end and va_arg.

The macro va_list represents an abstract datatype that can store the "unnamed" arguments of the function call (those that are captured by the "..."). To use it, you must first initialize it, using va_start() macro:

va_list argptr; /* declaration of the unnamed arguments list */
va_start(argptr, num); /* the initialization of the list */

The second parametar of va_start() must be the last named parameter of the function (in your case, this is num, which is the only named parameter provided). After the initialization, you can extract the unnamed arguments from the argptr list one by one, using va_arg() macro:

answer += va_arg(argptr, int); 

Each call of va_arg() returns the next argument from argptr, interpreting it as int (or any other type that is provided as the second argument of va_arg()). Notice that there is no type-checking and there is no way to be sure that the caller has actually provided the arguments of correct types.

Finally, the list should be released at the end by calling va_end(argptr) before returning.