我在C中实现了一些基本的数据结构,我发现如果我从函数中省略了返回类型并调用该函数,则编译器不会生成错误.我编译cc file.c并没有使用-Wall(所以我错过了警告)但在其他编程语言中这是一个严重的错误,程序将无法编译.
根据Graham Borland的要求,这是一个简单的例子:
int test()
{
printf("Hi!");
}
int main()
{
test();
}
Run Code Online (Sandbox Code Playgroud)
这是因为在C中,任何变量/函数都是隐式的int.
这是你可以使用同样的原因register,而不是register int,或unsigned代替unsigned int,auto而不是auto int和,static而不是static int.我个人总是明确地对我的变量进行限定int,但不管你是否这样做都是你的选择.
C是一种古老的语言,在引入时,返回的整数很常见,是函数的默认返回类型.人们后来开始意识到,对于更复杂的返回类型,最好指定int以确保您不会忘记返回类型,但为了保持与旧代码的向后兼容性,C无法删除此默认行为.相反,大多数编译器会发出警告.
如果函数到达没有return语句的结尾,则返回一个未定义的值,除非在main函数中返回0.这与上述原因相同.
/* implicit declaration of printf as: int printf(int); */
/* implicit int type */
main()
{
printf("hello, world\n");
} /* implicit return 0; */
Run Code Online (Sandbox Code Playgroud)