wcstombs

va_arg, va_start, va_end, and va_copy

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

va_copy( ) was added by C99.

The va_arg( ), va_start( ), and va_end( ) macros work together to allow a variable number of arguments to be passed to a function. The most common example of a function that takes a variable number of arguments is printf( ). The type va_list is defined by <stdarg.h>, or <cstdarg> for C++.

The general procedure for creating a function that can take a variable number of arguments is as follows. The function must have at least one known parameter, but may have more, prior to the variable parameter list. The rightmost known parameter is called the last_parm. The name of last_parm is used as the second parameter in a call to va_start( ). Before any of the variable-length parameters can be accessed, the argument pointer argptr must be initialized through a call to va_start( ). After that, parameters are returned via calls to va_arg( ), with type being the type of the next parameter. Finally, once all the parameters have been read and prior to returning from the function, a call to va_end( ) must be made to ensure that the stack is properly restored. If va_end( ) is not called, a program crash is very likely.

Programming Tip 

The proper use of va_start( ), va_end( ), and va_arg( ) is best illustrated with an example. This program uses sum_series( ) to return the sum of a series of numbers. The first argument contains a count of the number of arguments to follow. In this example, the first five elements of the following series are summed:

½+1/4+1/8+1/16 +1/2n . . .

The output displayed is '0.968750'.

/* Variable length argument example - sum a series.*/ #include <stdio.h> #include <stdarg.h> double sum_series(int, ...); int main(void) {   double d;   d = sum_series(5, 0.5, 0.25, 0.125, 0.0625, 0.03125);   printf("Sum of series is %f\n",d);   return 0; } double sum_series(int num, ...) {   double sum = 0.0, t;   va_list argptr;   /* initialize argptr */   va_start(argptr, num);   /* sum the series */   for(; num; num--) {    t = va_arg(argptr, double);    sum += t;   }   /* do orderly shutdown */   va_end(argptr);   return sum; }

The va_copy( ) macro copies the argument list in source to target.

A related function is vprintf( ).




C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net