Han*_*sir 16 c printf arguments
printf如何处理其参数?我知道在C#中我可以使用params关键字来做类似的事情,但我无法在C中完成它?
Jus*_*ier 18
这种函数称为可变函数.您可以使用C语言声明一个...,如下所示:
int f(int, ... );
Run Code Online (Sandbox Code Playgroud)
然后va_start,您可以使用,va_arg和va_end使用参数列表.这是一个例子:
#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\n",maxof(3, i, j[42], 0));
}
Run Code Online (Sandbox Code Playgroud)
此功能在函数中称为可变参数.你必须包含stdarg.h头文件; 然后在函数体内使用va_list类型和va_start,va_arg和va_end函数:
void print_arguments(int number_of_arguments, ...)
{
va_list list;
va_start(list, number_of_arguments);
printf("I am first element of the list: %d \n", va_arg(list, int));
printf("I am second element of the list: %d \n", va_arg(list, int));
printf("I am third element of the list: %d \n", va_arg(list, int));
va_end(list);
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用你的函数:
print_arguments(3,1,2,3);
Run Code Online (Sandbox Code Playgroud)
将打印出以下内容:
I am first element of the list: 1
I am second element of the list: 2
I am third element of the list: 3
Run Code Online (Sandbox Code Playgroud)
只是为了完成故事gcc(不确定其他编译器)支持
#define FUNC(X,Y,...) wiz(X,Y, ##__VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)
允许可变参数宏