Such a function is called a variadic function. You may declare one in C using ...
, like so:
int f(int, ... );
You may then use va_start
, va_arg
, and va_end
to work with the argument list. Here is an example:
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
void f(void);
main(){
f();
}
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
",maxof(3, i, j[42], 0));
}
For more information, please see The C Book and stdarg.h.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…