函数没有在C中指定的返回类型

我在C中遇到了这段代码:

#include  main( ) { int i = 5; workover(i); printf("%d",i); } workover(i) int i; { i = i*i; return(i); } 

我想知道函数“修井”的声明是如何有效的? 当我们没有提到函数的返回类型时会发生什么? (我们可以返回任何东西吗?)。参数也只是一个变量名,这是如何工作的?

如果未指定返回类型或参数类型,则C将隐式声明为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 (在Cygwin终端上尝试它,因为我现在没有我的linux系统)

我得到以下警告:

 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] } ^ 
  1. 第一个和第三个说, return type defaults to 'int' ,这意味着如果你没有指定一个返回类型,编译器将隐式声明它为int
  2. 第二个说, implicit declaration of function 'workover'因为编译器不知道什么是workover
  3. 第三个警告很容易理解,如果你修复第一个警告就会消失。

你应该这样做:

 #include  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 }