C变量函数:如何指定给va_arg的类型
在printf这样的函数中,我们使用C变量函数:如何指定给va_arg的类型,c,variadic-functions,C,Variadic Functions,在printf这样的函数中,我们使用stdarg.h来处理可变参数 void print(int args,...){ va_list ap; va_start(ap, args); int i = 0; for(i=0; i<args; i++){ printf("%d\n",va_arg(ap, int)); } va_end(ap); } 类型在C中不是一等公民 但是您不必关心太多类型:您可以安全地从无符号转换为有符号
stdarg.h
来处理可变参数
void print(int args,...){
va_list ap;
va_start(ap, args);
int i = 0;
for(i=0; i<args; i++){
printf("%d\n",va_arg(ap, int));
}
va_end(ap);
}
类型在C中不是一等公民 但是您不必关心太多类型:您可以安全地从
无符号
转换为有符号
,反之亦然,char*
和void*
,因此对于基本printf,您必须处理:
- 煤焦
- 短
- int
- 长的
- 浮动
- 双重的
- 空虚*
union
救援
typedef union
{
char as_char;
short as_short;
int as_int;
long as_long;
float as_float;
double as_double;
void* as_ptr;
} t_value;
typedef enum {
CHAR_T,
INT_T,
/* It goes on */
...
} t_type;
t_value get_value(va_list ap, t_type type) {
/* You can't avoid this step, there is no way to iterate over types */
switch (type) {
case T_CHAR:
return va_arg(ap, char);
case T_INT:
/* ... */
}
}
然后您只需创建一个查找表,为每个有效的格式说明符存储函数指针和
t\u类型。我不知道是什么意思,但如何动态编码?使用不同类型调用va_arg的语法是什么?
,我做了一些类似的事情,所以我可能会提供帮助,但我需要澄清。如果我们有va_arg(ap,int),我们只能传递int。那么如何使用与当前参数类型相同的va_arg(ap,TYPE)呢?正是如此va_arg(ap,char*)char*
等等。问题解决了吗?还没有。看,我不能对所有类型使用很多ifs或开关盒。相反,我必须使用函数指针数组,就像我在文章中所展示的那样。我知道我必须使用va_arg(ap,char*)
进行char*
等操作,但要以我想要的方式进行操作则更为复杂。对于va_arg,我有两个解决方案,在一个结构中,我将有一个函数指针+1)avoid*
2)aunion
,如解释的和。还在想办法。。。
typedef union
{
char as_char;
short as_short;
int as_int;
long as_long;
float as_float;
double as_double;
void* as_ptr;
} t_value;
typedef enum {
CHAR_T,
INT_T,
/* It goes on */
...
} t_type;
t_value get_value(va_list ap, t_type type) {
/* You can't avoid this step, there is no way to iterate over types */
switch (type) {
case T_CHAR:
return va_arg(ap, char);
case T_INT:
/* ... */
}
}