在C程序为什么编译甚至return语句缺失的情况? [英] Why do programs in C compile even when the return statement is missing?

查看:136
本文介绍了在C程序为什么编译甚至return语句缺失的情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实施一些C基本数据结构,我发现,如果我省略一个函数,调用该函数编译器不会生成一个错误的返回类型。我与 CC file.c中编并没有使用 -Wall (所以我错过了警告),但在其他编程语言,这是一个严重的错误,程序将无法编译。

每格雷厄姆Borland的要求,这里有一个简单的例子:

  INT测试()
{
  的printf(你好!);
}诠释的main()
{
    测试();
}


解决方案

C是一种古老的语言,而当时据介绍,返回的整数是足够常见的是一个函数的默认返回类型。后来人们开始认识到更复杂的返回类型,这是最好指定INT,以确保你是不是忘了返回类型,但为了保持与旧code向后兼容性,C无法删除此默认行为。相反,大多数编译器发出警告。

如果函数到达无除了在则返回一个未定义的值return语句结束主函数,则返回0。这具有与上述相同的理由。

  / *隐式声明的printf为:INT的printf(INT); * // *隐含的int类型* /
主要()
{
    的printf(你好,世界\\ n);
} / *隐式返回0; * /

I'm implementing some basic data structures in C and I found out that if I omit the return type from a function and call that function the compiler doesn't generate an error. I compiled with cc file.c and didn't use -Wall (so I missed the warning) but in other programming languages this is a serious error and the program won't compile.

Per Graham Borland's request, here's a simple example:

int test() 
{
  printf("Hi!");
}

int main() 
{ 
    test();
}

解决方案

C is an old language and at the time it was introduced, returning integers was common enough to be the default return type of a function. People later started realizing that with more complicated return types, it was best to specify int to be sure you are not forgetting the return type, but in order to maintain backwards compatibility with old code, C could not remove this default behavior. Instead most compilers issue warnings.

If the function reaches the end without a return statement an undefined value is returned except in the main function, 0 is returned. This has the same reason as above.

/* implicit declaration of printf as: int printf(int); */

/* implicit int type */
main()
{
    printf("hello, world\n");
} /* implicit return 0; */

这篇关于在C程序为什么编译甚至return语句缺失的情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆