va_arg()

Syntax:

#include <stdarg.h>
type va_arg( va_list argptr, type );
void va_end( va_list argptr );
void va_start( va_list argptr, last_parm );



Description:
The va_arg() macros are used to pass a variable number of arguments to a function.

1. First, you must have a call to va_start() passing a valid va_list and the mandatory first argument of the function. This first argument describes the number of parameters being passed.
2. Next, you call va_arg() passing the va_list and the type of the argument to be returned. The return value of va_arg() is the current parameter.
3. Repeat calls to va_arg() for however many arguments you have.
4. Finally, a call to va_end() passing the va_list is necessary for proper cleanup.

Example:

int sum( int, ... );
int main( void ) {
    
  int answer = sum( 4, 4, 3, 2, 1 );
  printf( "The answer is %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 );
}

OUTPUT: Displays 10, which is 4+3+2+1.



Related Topics:
None

Vadim avatar

Vadim