c - 两个带有 void 和空参数列表的函数声明

标签 c function parameters void

我想知道为什么会出现下面的代码:

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/

相关文章:

r - 在具有构面和多个几何图形的函数中使用 ggplot

java - 我的子类正在从其父类(super class)传递值

php - 警告 : mysql_query() expects parameter 2 to be resource

c - 使用 GCC 进行堆栈保护和粉碎

c - 在宏中使用 ({ ... }) 括号来吞掉分号

c++ - 如何将 CURLOPT_DNS_CACHE_TIMEOUT 与共享 DNS 缓存一起使用

javascript - 函数中是否需要指定参数 "e"?

c - 如何将SIP消息内容传递到C应用程序中

c - 将结构变量传递给函数

xml - XSLT - 将字符串附加到变量并将其打印在不同的文件中