gpt4 book ai didi

c - ANSI C 函数声明是如何改进旧的 Kernighan 和 Ritchie 风格的?

转载 作者:太空狗 更新时间:2023-10-29 14:54:10 26 4
gpt4 key购买 nike

关于 ANSI C 函数声明,这与旧的 K&R 风格相比有何改进?我知道它们之间的区别,我只是想知道使用旧样式会出现什么问题以及新样式是如何改进的。

最佳答案

旧式函数声明,尤其是不允许对调用进行编译时检查。

例如:

int func(x, y)
char *x;
double y;
{
/* ... */
}

...

func(10, 20);

当编译器看到调用时,它不知道函数 func 的参数类型,因此无法诊断错误。

对比:

int better_func(char *x, double y) {
/* ... */
}

...

better_func(10, 20);

将导致编译器错误消息(或至少是警告)。

另一个改进:原型(prototype)使得函数的参数类型为 float 和整数类型比 int 更窄(第 3 个 char 类型和两个 short 类型)。没有原型(prototype),float 被提升为 double,窄整数类型被提升为 intunsigned int .对于原型(prototype),float 参数作为 float 传递(除非函数是可变的,如 printf,在这种情况下旧规则适用可变参数)。

C Rationale文档在第 6.7.5.3 节中对此进行了讨论,可能比我讨论的要好:

The function prototype mechanism is one of the most useful additions to the C language. The feature, of course, has precedent in many of the Algol-derived languages of the past 25 years. The particular form adopted in the Standard is based in large part upon C++.

Function prototypes provide a powerful translation-time error detection capability. In traditional C practice without prototypes, it is extremely difficult for the translator to detect errors (wrong number or type of arguments) in calls to functions declared in another source file. Detection of such errors has occurred either at runtime or through the use of auxiliary software tools.

In function calls not in the scope of a function prototype, integer arguments have the integer promotions applied and float arguments are widened to double. It is not possible in such a call to pass an unconverted char or float argument. Function prototypes give the programmer explicit control over the function argument type conversions, so that the often inappropriate and sometimes inefficient default widening rules for arguments can be suppressed by the implementation.

还有更多;去读吧。

关于c - ANSI C 函数声明是如何改进旧的 Kernighan 和 Ritchie 风格的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com