传递一个省略号到另一个可变参数函数 [英] Passing an ellipsis to another variadic function

查看:125
本文介绍了传递一个省略号到另一个可变参数函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约30个可变参数的功能。每一个接受作为最后一个参数,例如路径:

I have approximately 30 variadic functions. Each one accepts a path as the final argument, e.g.:

bool do_foo(struct *f, int q, const char *fmt, ...)

在每个函数,我要检查扩展格式是小于或等于某一尺寸。所以,我觉得自己复制/粘贴code相同的块来检查多少个字符 vsnprintf()未打印,设置错误号相应保释出来写的。

In each function, I have to check that the expanded format is less then or equal to a certain size. So, I find myself copy / pasting the same chunk of code to check for how many characters vsnprintf() didn't print, set errno accordingly and bail out of the write.

我希望做的是写一个函数来做到这一点,这都将返回一个被称为是一个安全的大小,或新初始化字符串失败,这可能与NULL进行检查静态分配(扩大)字符串。此次抽查还必须确定该字符串是一个绝对或相对路径,从而影响字符串的安全大小。这是一个很多重复的code和它开始闻。

What I would like to do is write a function to do this, which would return a statically allocated (expanded) string that is known to be a safe size, or newly initialized string on failure, which could be checked against NULL. The checks also have to determine if the string is an absolute or relative path, which influences the safe size of the string. It's a lot of duplicate code and it's starting to smell.

有没有办法,我可以从我的函数入口到另一个函数传递省略号的内容的方式吗?还是我叫的va_start(),然后再通过的va_list 来辅助功能?

Is there a way that I can pass the contents of the elipsis from my function's entry to another function? Or do I have to call va_start() first, and then pass the va_list to the helper function?

编辑:

我并不是在所有反对通过了的va_list 来帮手,我只是想确保没有别的存在。在我看来,编译器理解其中可变参数开始,所以我只是好奇,如果我可以告诉它通过他们。

I am not at all opposed to passing the va_list to the helper, I just wanted to make sure that nothing else existed. It seems to me the compiler understands where the variadic arguments begin, so I was just curious if I could tell it to pass them along.

推荐答案

您不能,你只能传递参数为的va_list 。请参阅 comp.lang.c常见问题解答

You can't, you can only pass the arguments as a va_list. See the comp.lang.c FAQ.

在一般情况下,如果你正在编写C可变参数的函数(即,它带有可变数量的参数的函数),你应该写的每个函数的两个版本:一个它接受一个省略号( ... ),和一个这需要一个的va_list 。该版本以省略号应该叫的va_start ,调用版本采取了的va_list ,电话 va_end用来,并返回。没有必要为函数的两个版本之间code复制,因为一个叫对方。

In general, if you're writing variadic functions (that is, functions which take a variable number of arguments) in C, you should write two versions of each function: one which takes an ellipsis (...), and one which takes a va_list. The version taking an ellipsis should call va_start, call the version taking a va_list, call va_end, and return. There's no need for code duplication between the two versions of the function, since one calls the other.

这篇关于传递一个省略号到另一个可变参数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆