【问题标题】:Why are the parameter types declared outside the parenthesis?为什么要在括号外声明参数类型?
【发布时间】:2010-04-09 12:27:02
【问题描述】:
有时我看到函数定义如下:
read_dir(dir)
char *dir;
{
DIR * dirp;
struct dirent *d;
/* open directory */
dirp = opendir(dir);
......... so on
这里声明的重要性是什么
char *dir;
在函数名之后立即声明指针然后启动函数体的含义是什么。
【问题讨论】:
标签:
c
function
coding-style
【解决方案1】:
这是一种较旧的 C 语法,称为“K&R C”,因为它在 legendary book 的原始版本中就是这样出现的。
以前是这样写的:
foo(a, b)
int a;
int b;
{
}
现在
int foo(int a, int b)
{
}
【解决方案2】:
只是“旧式”,K&R C 函数定义(参见Kernighan & Ritchie's book,通常简称为Kernighan & Ritchie。)
您提到的代码可能是在 80 年代末或 90 年代初编写的,考虑到可移植性(即与旧编译器的兼容性,可能在更“外来”的平台上)。
即使在 1989 年 C 标准发布之后,多年来 K&R C 仍然被认为是 C 程序员在需要最大可移植性时限制自己的“最低公分母”,因为许多旧编译器仍在使用中,并且因为精心编写的 K&R C 代码也可以是合法的 Standard C。
有些人可能认为编译器仍然支持的K&R风格的函数定义更具可读性,事实上这不一定是正确的;比较:
some_function(param1,param2,param3)
char *param1; /* param1 comment */
int param2; /* param2 comment */
short param3; /* param3 comment */
{
}
与
/* notice also that return type is explicitly specified now */
int
some_function(
char *param1, /* param1 comment */
int param2, /* param2 comment */
short param3 /* param3 comment */
)
{
}
K&R 风格的函数定义已自 1989 年以来已过时;看
C90 标准中的第 6.9.5 节“函数定义”。