在 K&R 第 6.3 章中,函数 getword() 的定义如下:
int getword(char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w = words;
while(isspace(c=getch()))
;
if(c!= EOF)
*w++; = c;
if(isalpha(c)) {
*w = '\0';
return c;
}
for(;--lim > 0; w++)
if(!isalnum(*w)getch()){
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}
我不明白该行的语法
int c, getch(void);
我还是第一次看到这个。为什么要将函数声明为 int ?在调用函数之前插入函数原型(prototype)难道还不够吗?
最佳答案
想想线条
int c, getch(void);
相当于
int c;
int getch(void);
也就是说,它是一个名为 c
的 int
变量的声明,后跟一个名为 getch
的函数原型(prototype),该函数不带参数,并且返回int
。
如本例所示,C 语言中的“声明”和“函数原型(prototype)”之间没有硬性界限。函数原型(prototype)仅仅是一个声明,它声明了一个函数类型,其中包括其参数的类型。
像这样声明具有局部作用域的函数原型(prototype)有点不寻常,但完全没有错误。通常,函数原型(prototype)在源文件的“顶部”声明,具有全局作用域,位于任何函数之外。 (事实上,通常情况下,函数原型(prototype)是在头文件中声明的。)
Why is it declaring a function as int?
嗯,因为 getch
函数确实返回 int
。
Shouldn't be enough to insert prototypes of functions before calling them?
是的,这正是 this like 所做的——这一行确实包含一个函数原型(prototype),它在调用之前声明了 getch
函数。
最重要的是,C 中的每个函数声明都是“外部”的,无论它出现在函数内部还是外部,无论它是否包含存储类说明符 extern
。
关于c - 将函数重新声明为 int K&R 6.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58374993/