可变参数函数的使用
使用有什么好处 可变参数函数
void fun(int i, ...);
而不是传递指向数组的指针?
void fun(int i*);
什么时候首选可变参数函数?
What are the benefits of using
variadic functions
void fun(int i, ...);
instead of passing a pointer to an array?
void fun(int i*);
When are variadic functions preferred?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须首先显式创建数组。另外,如果要指定不同类型的参数也会有问题。
可变参数函数不需要创建任何数组,并且可以处理不同的类型。
举个例子,如果我总是必须先创建一些数组,我就不能直接使用 printf 函数。
另一方面,我想,在大多数情况下,它只是一种语法糖形式。
You have to explicitly create the array first. In addition, it would be problematic if you wanted to specify parameters of different types.
Variadic functions do not require creating any array and they can deal with different types.
As an example, I could not bare to use the
printf
-functions if I always had to create some array first.On the other hand, in most cases it's just a form of syntactic sugar, I suppose.
指向数组的指针假定参数的预定义类型(或结构,如果有几种不同的类型)。
当您事先不知道参数的类型是什么,并且您使用预定义参数的提示来获取该信息(例如
printf
的格式字符串)时,可以使用可变参数函数。Pointer to array assumes predefined type of the parameter (or struct, if its several different types).
Variadic functions are used when you don't know ahead of time what would the type of the parameter be, and you use a hint of the predefined parameters to get that knowledge (like the format string for
printf
).另外,您不想在可变参数函数中传递数组,因为您还想传递其大小。例如:
不过,要点是可变参数函数允许传递许多不同的类型。
Also, you don't want to pass an array in a variadic function, as you would also want to pass in its size. e.g:
The main point, though, is that variadic functions allow many different types to be passed.
我建议您不要使用可变参数函数。然而它们可能很有用。例如,在模板元编程技术中实现编译时查询。
函数传递适当数量的参数或者那些
参数有适当的类型。因此,运行时调用
传递不适当参数的可变参数函数会产生
未定义的行为。
c++ 你可以找到面向对象的替代方案(也是一种
问题)。
va_arg()
或忽略va_end(ap)
调用可能会导致程序崩溃。接近未定义行为的示例:
我的工作是围绕 sqlite C api 创建一个面向对象的包装器。
我在这里:我创建了一个用于执行 sqlite 查询的奇特接口,它是这样的:
一方面这是很棒且奇特的,但是:如果您的参数类型错误,您会立即遇到未定义的行为。例如:
将导致未定义的行为。
I would suggest you to simply not use variadic functions. However they can be useful. For example in template metaprogramming techniques to implement compile-time querys.
function passes an appropriate number of arguments or that those
arguments have appropriate types. Consequently, a runtime call to a
variadic function that passes inappropriate arguments yields
undefined behavior.
c++ you are able to find object oriented alternatives (also one
issue).
va_arg()
one time to many or omitting theva_end(ap)
call can crash your program.Example of being close to undefined behavior:
It was my job to crate a object-oriented wrapper around the sqlite C api.
Here I am: I created a fancy interface for executing sqlite querys it was something like that:
This is on one side awesome and fancy but: You immediately encounter undefined behavior if your parameter types are wrong. For example:
Will result in undefined behavior.