C++ 或 C 中的 foo(void) 和 foo() 之间有区别吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a difference between foo(void) and foo() in C++ or C?
提问by Landon
Consider these two function definitions:
考虑这两个函数定义:
void foo() { }
void foo(void) { }
Is there any difference between these two? If not, why is the void
argument there? Aesthetic reasons?
这两者有什么区别吗?如果没有,为什么会有void
争论?审美原因?
回答by DrPizza
In C:
在C 中:
void foo()
means "a functionfoo
taking an unspecified number of arguments of unspecified type"void foo(void)
means "a functionfoo
taking no arguments"
void foo()
表示“foo
采用未指定数量的未指定类型参数的函数”void foo(void)
意思是“一个foo
不带参数的函数”
In C++:
在C++ 中:
void foo()
means "a functionfoo
taking no arguments"void foo(void)
means "a functionfoo
taking no arguments"
void foo()
意思是“一个foo
不带参数的函数”void foo(void)
意思是“一个foo
不带参数的函数”
By writing foo(void)
, therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an extern "C"
if we're compiling C++).
foo(void)
因此,通过编写,我们实现了跨两种语言的相同解释并使我们的头文件多语言(尽管我们通常需要对头文件做更多的事情以使其真正跨语言;即,extern "C"
如果我们正在编译,将它们包装在一个C++)。
回答by Kyle Cronin
I realize your question pertains to C++, but when it comes to C the answer can be found in K&R, pages 72-73:
我知道您的问题与 C++ 有关,但是当涉及到 C 时,答案可以在 K&R,第 72-73 页中找到:
Furthermore, if a function declaration does not include arguments, as in
double atof();
that too is taken to mean that nothing is to be assumed about the arguments of atof; all parameter checking is turned off. This special meaning of the empty argument list is intended to permit older C programs to compile with new compilers. But it's a bad idea to use it with new programs. If the function takes arguments, declare them; if it takes no arguments, use void.
此外,如果函数声明不包含参数,如
double atof();
这也意味着对 atof 的参数没有任何假设;关闭所有参数检查。空参数列表的这种特殊含义旨在允许旧的 C 程序使用新的编译器进行编译。但是将它与新程序一起使用是个坏主意。如果函数接受参数,则声明它们;如果不需要参数,则使用 void。
回答by Paul Tomblin
In C, you use a void in an empty function reference so that the compiler has a prototype, and that prototype has "no arguments". In C++, you don't have to tell the compiler that you have a prototype because you can't leave out the prototype.
在 C 中,您在空函数引用中使用 void 以便编译器具有原型,并且该原型“没有参数”。在 C++ 中,您不必告诉编译器您有原型,因为您不能遗漏原型。