有void和空参数列表的两个函数声明 [英] Two function declarations with void and empty argument list

查看:365
本文介绍了有void和空参数列表的两个函数声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  void foo(void);我想知道为什么下面的代码: 
void foo()
{
}

有效GCC。在C中,不存在重载和上面的声明(事实上,其中一个是定义)声明了两个不同的函数(第一个函数不接受任何参数,第二个函数可以接受任意数量的参数然而,如果我们为第一个函数提供一个定义:

 <$> 

c $ c $> void foo(void)
{
}
void foo()
{
}
pre>

由于重新定义,此次编译失败。 但仍,第一个代码是正确的,可能会令人困惑,如下所示:

  void foo (空隙); 

int main(void)
{
foo(); // OK
// foo(5); //错,尽管 - >定义< - 允许它
}

void foo()
{
}

 

void foo(int);
void foo()//错误:参数个数不匹配原型
{
}

我认为编译器的行为比我第一个前面的代码有点奇怪。 int 不等于(/ *空列表* /)并且都不是 void



任何人都可以解释这一点吗?

解决方案

关于函数声明符的标准:


(6.7.6.3/10)void类型的一个未命名参数的特殊情况为
只有列表中的项指定函数没有参数。

(6.7.6.3/14)标识符列表仅声明
参数的标识符的功能。函数声明符
中的空列表是该函数定义的一部分,它指定
函数没有参数。

所以声明和定义的声明实际上是兼容的,因此引用了相同的函数(当然不会发生重载,因为C中不存在这样的函数)。 b $ b

I'd like to know why the following code:

void foo(void);
void foo()
{
}

is valid in gcc. In C, there is no such thing as overloading and above declarations (in fact, one of them is a definition) declare two different functions (the first one doesn't take any arguments, the second one could take any number of arguments of any types).

However, if we provide a definition for the first function:

void foo(void)
{
}
void foo()
{
}

a compilation fails this time due to redefinition. But still, the first code is correct and might be confusing as in the following:

void foo(void);

int main(void)
{
    foo();      //OK
    //foo(5);   //Wrong, despite ->the definition<- allows it
}

void foo()
{
}

On the other hand, something like this is invalid straightaway:

void foo(int);
void foo() //error: number of arguments doesn't match prototype
{
}

I think the compiler's behavior is kinda weird in comparison to my first foregoing code. int isn't equal to (/*empty list*/) and neither is void.

Can anyone explain this ?

解决方案

Quoting a late draft of the standard about function declarators:

(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.

So the declarators of the declaration and definition are in fact compatible, and thus refer to the same function (with no overloading taking place of course, as such a thing does not exist in C.)

这篇关于有void和空参数列表的两个函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆