如何处理的printf它的参数? [英] How does printf handle its arguments?
本文介绍了如何处理的printf它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何处理的printf它的参数?我知道,在C#中,我可以使用 PARAMS
关键字做同样的事情,但我不能在C做?
How does printf handle its arguments? I know that in C# I can use params
keyword to do something similar but I can't get it done in C ?
推荐答案
这样的函数称为可变参数函数。你可以使用用C定义一个 ...
,就像这样:
Such a function is called a variadic function. You may declare one in C using ...
, like so:
int f(int, ... );
您可以再使用的va_start
,的va_arg
和 va_end用来
参数列表工作。下面是一个例子:
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\n",maxof(3, i, j[42], 0));
}
For more information, please see The C Book and stdarg.h.
这篇关于如何处理的printf它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文