我在C语言中发现了这段代码:
#include <stdio.h>
main( )
{
int i = 5;
workover(i);
printf("%d",i);
}
workover(i)
int i;
{
i = i*i;
return(i);
}
我想知道函数"workover"的声明如何是有效的?如果我们没有提到函数的返回类型会发生什么呢?(我们可以返回任何东西吗?)参数也只是一个变量名,这是如何工作的?
我在C语言中发现了这段代码:
#include <stdio.h>
main( )
{
int i = 5;
workover(i);
printf("%d",i);
}
workover(i)
int i;
{
i = i*i;
return(i);
}
int
。这是早期C语言版本(C89和C90)的“特性”,但现在通常被认为是不良实践。自C99标准(1999年)以来不再允许这样做,因此针对C99或更高版本的编译器可能会给出类似以下警告的警告:program.c: At top level:
program.c:8:1: warning: return type defaults to ‘int’
workover(i)
^
在旧版本的C语言中,使用函数声明语法是有效的,因此代码片段 "workover(i) int i;" 等价于 "workover(int i)"。不过,根据使用的编译器选项,它可能仍会生成警告甚至错误。
$ gcc common.c -o common.exe -Wall
(由于我现在没有我的Linux系统,因此尝试在Cygwin终端上执行),我会得到以下警告:common.c:3:1: warning: return type defaults to ‘int’ [-Wreturn-type]
main( )
^
common.c: In function ‘main’:
common.c:6:2: warning: implicit declaration of function ‘workover’ [-Wimplicit-f unction-declaration]
workover(i);
^
common.c: At top level:
common.c:9:1: warning: return type defaults to ‘int’ [-Wreturn-type]
workover(i)
^
common.c: In function ‘main’:
common.c:8:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
返回类型默认为'int'
这意味着如果您没有指定返回类型,编译器将隐式声明其为int
。函数'workover'的隐式声明
因为编译器不知道workover
是什么。您应该按照这种方式进行操作:
#include <stdio.h>
int workover(int);
int i;
int main(void)
{
int i = 5;
workover(i);
printf("%d",i); //prints 5
return 0;
}
int workover(int i)
{
i = i*i; //i will have local scope, so after this execution i will be 25;
return(i); //returns 25
}
int
。"这就是为什么会产生警告的原因。 - Frxstremworkover(i) int i;
不是原型,但workover(int i)
是。这类似于int main()
和int main(void)
之间的区别。 - M.M