C ++或者C中的foo(void)和foo()之间有区别吗?
时间:2020-03-05 18:49:46 来源:igfitidea点击:
考虑以下两个函数定义:
void foo() { } void foo(void) { }
两者之间有什么区别吗?如果不是,那为什么会出现void
参数呢?审美原因?
解决方案
回答
在C语言中,我们可以在空函数引用中使用void,以便编译器具有原型,而该原型具有"无参数"。在C ++中,我们不必告诉编译器我们有原型,因为我们不能遗漏原型。
回答
我意识到问题与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.
回答
在C中:
- void foo()的意思是"函数foo接受未指定类型的未指定数量的参数"
- void foo(void)的意思是"不带参数的函数foo"
在C ++中:
- void foo()的意思是"不带参数的函数foo"
- void foo(void)的意思是"不带参数的函数foo"
因此,通过编写foo(void),我们可以在两种语言中实现相同的解释,并使标头变为多语言(尽管我们通常需要对标头做更多的事情才能使它们真正成为跨语言;也就是说,将它们包装在如果我们正在编译C ++,则为extern" C"
)。