9.9. Variable numbers of argumentsIt is often desirable to implement a function where the number of
arguments is not known, or is not constant, when the function is written.
Such a function is In order to access the arguments within the called function, the functions
declared in the Before any attempt can be made to access a variable argument list,
#include <stdarg.h> void vastart(valist ap, parmN); The Once initialized, the arguments supplied can be accessed sequentially by means of the va arg macro. This is peculiar because the type returned is determined by an argument to the macro. Note that this is impossible to implement as a true function, only as a macro. It is defined as #include <stdarg.h> type va arg(va list ap, type); Each call to this macro will extract the next argument from the argument
list as a value of the specified type. The The behaviour is also undefined if The type argument must be a type name which can be converted
into a pointer to such an object simply by appending a When all the arguments have been processed, the The entire argument list can be re-traversed by calling
#include <stdarg.h> void va_end(va list ap); The following example shows the use of
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
int maxof(int, ...) ;
void f(void);
main(){
f();
exit(EXIT SUCCESS);
}
int maxof(int n args, ...){
register int i;
int max, a;
va_list ap;
va_start(ap, n args);
max = va_arg(ap, int);
for(i = 2; i <= n_args; i++) {
if((a = va_arg(ap, int)) > max)
max = a;
}
va_end(ap);
return max;
}
void f(void) {
int i = 5;
int j[256];
j[42] = 24;
printf("%d\n",maxof(3, i, j[42], 0));
}Example 9.6 |
The C BookThis book is published as a matter of historical interest. Please read the copyright and disclaimer information. GBdirect Ltd provides up-to-date training and consultancy in C, Embedded C, C++ and a wide range of other subjects based on open standards if you happen to be interested. |
|
West Yorkshire Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday South East Regional Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday Please note: |