2017-06-06 125 views
4

声明两个函数为什么下面的代码可以通过GCC罐体C具有相同的名称,返回类型,但不同的参数

#include <stdio.h> 
int func(); 
int func(int a) { return 1; } 
int main() { 
    func(10); 
    return 0; 
} 

编译但是,如果我添加char func();,GCC说conflicting types for ‘func’

+0

与该问题不一样。我也认为这是一个重载,但为什么gcc接受该代码?代码不能编译的 – Steve

+0

。错误:函数声明不是原型[-Werror = strict-prototypes] ' –

+0

我使用gcc(GCC)4.9.3,也许警告不是默认的 – Steve

回答

10

这不是一个过载,因为你不能调用func()没有参数。这是兼容函数声明单一功能的特殊情况下,如在标准中描述:

If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions.

更改返回类型从intchar就是要打破这个规则的一种方式。打破它的另一种方式是比int提供其他的参数类型:

int func(); 
int func(char a) { return 1; } // Does not compile 

如果你想声明,不带任何参数的函数,则说明符应如下:

int func(void); 

现在声明func接受一个int会导致编译时错误:

int func(void); 
int func(int a) { return 1; } // Does not compile 
+0

你是对的! – Steve

1

你的第一个declarat离子是K & R声明,而下一个声明(含定义)是ANSI原型。

如果它们兼容,可以在KR decl和ANSI原型之间进行任意组合。

C型检查器将两者结合起来并保持ANSI原型。这被称为composite type

这里是复合类型是如何计算为&řDECL ANSI和K之间的组合:

6.2.7 Compatible type and composite type

3 ... If only one type is a function type with a parameter type list (a function prototype), the composite type is a function prototype with the parameter type list.

要检查2函数声明是否兼容一个必须从6.7.6.3 Function declarators

15 For two function types to be compatible, both shall specify compatible return types.146) Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types.

应用的规则

这就是为什么您的原型可以与K & R decl相结合,因为它们被认为是兼容的。

相关问题