为什么C标准不允许您从函数返回值? [英] Why C standards allow you not to return a value from a function?

查看:202
本文介绍了为什么C标准不允许您从函数返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在gcc中成功编译并执行了以下代码:

I have successfully compiled and executed the following code in gcc:

#include <stdio.h>

int foo()
{

}

int main()
{
    int i = 12345;
    i = foo();
    printf("i is: %d", i);
}

输出为:

i is: 0

所以gcc允许我不要从函数foo()返回,而使foo()返回0.

So gcc allowed me not to return from the function foo() and made foo() return 0.

此行为仅适用于gcc还是其他C标准也有(根据我的理解,gcc不符合任何C标准)?

Does this behavior only applies to gcc or do other C standards also have it (based on my understanding, gcc does not conform to any C standard)?

推荐答案

如果函数缺少返回语句¹,则C标准都不要求编译器产生错误或警告.

None of the C standards require the compiler to produce an error or warning if a function is missing a return statement¹.

在所有C标准中,如果控制流到达不带return的非void函数的末尾,然后使用该函数的返回值(如您的代码中),则行为是不确定的.

In all of the C standards the behaviour is undefined if control flow reaches the end of non-void function without a return and the return value of the function is then used (as in your code).

因此,如果允许"表示将其指定为合法的,明确定义的行为",则所有C标准都不允许您的代码.如果您只是说不需要实现就可以产生错误",那么所有这些都可以.

So if by "allow" you mean "specify it as legal, well-defined behaviour", none of the C standards allow your code. If you just mean "don't require an implementation to produce an error", all of them do.

请注意,如果更改foo的定义(而无需添加return),则示例程序中的i值可以轻松更改.您不能依靠它为0.在标准或GCC的实现中,都没有规则说如果没有返回,则返回0".根据标准,它是未定义的,并且在GCC中,那时的返回寄存器中将只发生任何事情.

Do note that the value of i in your example program can easily change if you change the definition of foo (without adding a return). You can not rely on it being 0. There is no rule that says "if there's no return, return 0" - neither in the standard nor in GCC's implementation. According to the standard it's undefined and in GCC it will just be whatever happens to be in the return register at that time.

¹在一般情况下,这是无法确定的.一个人可以做例如Java确实定义了规则,因此拒绝了一些其他有效的函数定义,但是没有C标准这样做.

¹ In the general case this would be undecidable. One could do what e.g. Java does and define the rules so that some otherwise valid function definitions are rejected, but none of the C standards do this.

这篇关于为什么C标准不允许您从函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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