C 函数调用 : Understanding the "implicit int" rule

标签 c function

If "a function" were compiled separately, the mismatch would not be detected, "the function" would return a double that main would treat as an int... In the light of what we have said about how declarations must match definitions this might seems surprising. The reason a mismatch can happen is that if there is no function prototype, a function is implicitly declared by its first appearance in an expression, such as

    sum += "the function"(line);

If a name that has not been previously declared occurs in an expression and is followed by a left parenthesis, it is declared by context to be a function name, the function is assumed to return an int, and nothing is assumed about its arguments.

对于模棱两可的问题,我事先表示歉意,但这是什么意思?

顺便说一下,这是 Brian W. Kernighan 和 Dennis M. Ritchie 的《C 编程语言》一书第 2 版第 73 页第 4.3 章。

最佳答案

K&R2 涵盖了该语言的 1989/1990 版本。当前的 ISO C 标准发布于 1999 2011,放弃了“隐式 int”规则,并要求您调用的任何函数都有一个可见的声明。编译器不一定默认强制执行此操作,但您应该能够请求更严格的警告——您绝对应该这样做。在编写良好的新代码中,规则是无关紧要的(但有必要理解它)。

一个例子:标准sqrt()函数在 <math.h> 中声明:

double sqrt(double);

如果您编写一个调用没有必需的#include <math.h> :

double x = 64.0;
double y = sqrt(x);

C90 编译器将假定 sqrt返回 int -- 它会生成代码来转换 int 的结果至 double .结果将是垃圾,或者可能是崩溃。

(您可以自己手动声明 sqrt,但这是错误的解决方案。)

所以不要那样做。始终包含您调用的任何函数所需的任何 header 。如果它确实返回 int,您可能会调用未声明的函数(如果您的编译器不强制执行严格的 C99 或 C11 语义,并且满足其他一些条件),但没有充分的理由这样做。

了解“隐式 int”规则对于理解旧代码或编写不当的代码的行为仍然有用,但您永远不应在新代码中依赖它。

关于C 函数调用 : Understanding the "implicit int" rule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8220463/

相关文章:

C# - 在 C# 中的等效数据类型中编码(marshal) char **

Javascript 使用异步加载本地 .txt 文件

c - 动态内存和指针参数

c - 使用指针作为函数参数来解析网络 'interfaces' 以进行读/写

c - 遍历多个文件对象

计算文件中 8 位符号的频率

c++ - 关于 Swift 中从 C 文件访问 "typedef void PaStream;"的正确语法有什么帮助吗?

Python 装饰器? - 有人可以解释一下吗?

c - printf 在内部是如何工作的?

c++ - C/C++ 中的 JSON <-> XML