c - 函数原型(prototype) - 关闭参数检查

标签 c function function-prototypes

从关于 C 的 K&R Book 中,我了解到如果函数原型(prototype)声明省略了参数(如 int foo();),类型和参数检查将被关闭,并且没有任何关于参数与旧版本的 C 兼容,因此它不会破坏遗留代码。

但是下面的代码会抛出原型(prototype)不匹配的编译错误:

#include <stdio.h>
void test();
int main(void) {
    test(34.5f);
}

void test(float a) {
    printf("%f\n", a);
}

错误:

C:\***.c:7:6: error: conflicting types for 'test'
 void test(float a) {
      ^

有什么解释吗?

最佳答案

当多次声明一个函数时,所有声明都必须具有兼容类型 (C11 6.2.7/2)。在您的代码中,f 被声明了两次 - 定义也算作声明。

“兼容函数类型”的定义在C11 6.7.6.3/15:

For two function types to be compatible, both shall specify compatible return types. 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. 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. If one type has a parameter type list and the other type is specified by a function definition that contains a (possibly empty) identifier list, both shall agree in the number of parameters, and the type of each prototype parameter shall be compatible with the type that results from the application of the default argument promotions to the type of the corresponding identifier. (In the determination of type compatibility and of a composite type, each parameter declared with function or array type is taken as having the adjusted type and each parameter declared with qualified type is taken as having the unqualified version of its declared type.)

因此 void test()void test(float) 是不兼容的。换句话说,在看到 void test(); 之后,任何原型(prototype)都必须仅使用默认参数提升未更改的类型。 float 在这些促销事件下变为 double

我相信自第一个 C 标准以来一直如此。

关于c - 函数原型(prototype) - 关闭参数检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42034962/

相关文章:

javascript - AJAX/Javascript 功能不起作用

powershell - 如何在 powershell 中创建函数原型(prototype)?

我可以为了分析目的人为地减慢 C trig 函数吗?

C、预设参数的函数指针

c - 在 C 语言中, `&function` 和 `function` 作为参数传递时有什么区别?

scala - 重载的方法值在scala中应用替代错误

perl - 让 perl 向前看子原型(prototype)

c++ - 为什么函数原型(prototype)在不需要时包含参数名称?

python - 使用 Python C-API 确定对象是否有效?

c++ - c 问题错误在此函数中使用统一化