本文介绍了类型安全的可变参数用C用gcc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很多时候,我想一个函数来接受可变数量的参数,以NULL结尾,例如
Many times I want a function to receive a variable number of arguments, terminated by NULL, for instance
#define push(stack_t stack, ...) _push(__VARARG__, NULL);
func _push(stack_t stack, char *s, ...) {
va_list args;
va_start(args, s);
while (s = va_arg(args, char*)) push_single(stack, s);
}
我可以指示GCC或铿锵,如果富接收非的char *
变量警告?类似的东西 __ __属性(格式)
,但对同一指针类型的多个参数。
Can I instruct gcc or clang to warn if foo receives non char*
variables? Something similar to __attribute__(format)
, but for multiple arguments of the same pointer type.
推荐答案
我知道你在想使用 __属性__((定点))
不知何故,但是这是一个红鲱鱼。
I know you're thinking of using __attribute__((sentinel))
somehow, but this is a red herring.
您需要的是做这样的事情:
What you want is to do something like this:
#define push(s, args...) ({ \
char *_args[] = {args}; \
_push(s,_args,sizeof(_args)/sizeof(char*)); \
})
它包装:
void _push(stack_t s, char *args[], int argn);
,你可以写的究竟的你会希望你能写出来的样子!
which you can write exactly the way you would hope you can write it!
然后就可以调用:
push(stack, "foo", "bar", "baz");
push(stack, "quux");
这篇关于类型安全的可变参数用C用gcc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!