Wiz*_*ard 56
K&R语法已过时,除非必须维护非常旧的代码,否则可以跳过它.
// K&R syntax
int foo(a, p)
int a;
char *p;
{
return 0;
}
// ANSI syntax
int foo(int a, char *p)
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
The*_*ock 23
传统的K&R风格声明/定义
当Kernighan和Ritchie首次发表"The C Programming Language"时,C还没有提供全功能原型.存在函数的前向声明,但唯一的目的是指示返回类型.对于返回的函数,int直到C99才需要它们.
通过C89,添加了函数原型的概念,该函数原型还指定了参数的类型(以及隐含的数字).由于原型也是一种函数声明,非官方术语"K&R函数声明"有时用于不是原型的函数声明.
// K&R declarations, we don't know whether these functions have parameters.
int foo(); // this declaration not strictly necessary until C99, because it returns int
float bar();
// Full prototypes, specifying the number and types of parameters
int foo(int);
float bar(int, float);
// K&R definition of a function
int foo(a)
int a; // parameter types were declared separately
{
// ...
return 0;
}
// Modern definition of a function
float bar(int a, float b)
{
// ...
return 0.0;
}
Run Code Online (Sandbox Code Playgroud)
意外K&R宣言
值得注意的是,C的新手在打算使用完整的原型时可能会意外地使用K&R声明,因为他们可能没有意识到必须将空参数列表指定为void.
如果声明并定义函数为
// Accidental K&R declaration
int baz(); // May be called with any possible set of parameters
// Definition
int baz() // No actual parameters means undefined behavior if called with parameters.
// Missing "void" in the parameter list of a definition is undesirable but not
// strictly an error, no parameters in a definition does mean no parameters;
// still, it's better to be in the habit of consistently using "void" for empty
// parameter lists in C, so we don't forget when writing prototypes.
{
// ...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
...那么你实际上没有给一个不带参数的函数的原型,而是一个K&R-style的声明,用于接受未知类型的未知数量的参数的函数.
AnT在这个答案中注意到一个类似的问题,即这个语法已被弃用但从C99开始仍然合法(并且函数指向具有未知数量和参数类型的函数仍然具有潜在的应用程序,尽管存在未定义行为的高风险); 因此,如果在没有适当原型的情况下声明或调用函数,兼容编译器最多会产生警告.
调用没有原型的函数不太安全,因为编译器无法验证您是否以正确的顺序传递了正确数量和类型的参数; 如果调用实际上不正确,则会导致未定义的行为.
当然,声明和定义无参数函数的正确方法是:
// Modern declaration of a parameterless function.
int qux(void); // "void" as a parameter type means there are no parameters.
// Without using "void", this would be a K&R declaration.
// Modern definition of a parameterless function
int qux(void)
{
// ...
return 0;
}
Run Code Online (Sandbox Code Playgroud)