我想知道为什么会出现下面的代码:
void foo(void);
void foo()
{
}
在 gcc 中有效。在 C 中,没有重载和上面的声明(实际上,其中一个是定义)声明两个不同的函数(第一个不接受任何参数,第二个可以接受任意数量的任何参数类型)。
但是,如果我们为第一个函数提供定义:
void foo(void)
{
}
void foo()
{
}
由于重新定义,这次编译失败。 但仍然,第一个代码是正确的,可能会造成混淆,如下所示:
void foo(void);
int main(void)
{
foo(); //OK
//foo(5); //Wrong, despite ->the definition<- allows it
}
void foo()
{
}
另一方面,像这样的东西是直接无效的:
void foo(int);
void foo() //error: number of arguments doesn't match prototype
{
}
与我前面的第一个代码相比,我认为编译器的行为有点奇怪。 int
不等于 (/*empty list*/)
也不等于 void
。
谁能解释一下?
最佳答案
引用关于函数声明符的最新标准草案:
(6.7.6.3/10) The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.
(6.7.6.3/14) An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.
所以声明和定义的声明符实际上是兼容的,因此引用相同的函数(当然没有发生重载,因为 C 中不存在这样的事情。)
关于c - 两个带有 void 和空参数列表的函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12022777/