如果一个函数没有返回值,有一个有效的返回类型,什么情况下可以为编译器扔垃圾? [英] If a function returns no value, with a valid return type, is it okay to for the compiler to throw garbage?

查看:122
本文介绍了如果一个函数没有返回值,有一个有效的返回类型,什么情况下可以为编译器扔垃圾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个函数具有非void的返回类型,函数不返回任何东西,那么我想,编译器将返回一个垃圾值(可能被视为一个未初始化的值)。它发生在编译​​的时候,为什么不应该扔一个错误。

If a function has a return type other than void, and the function does not return anything, then I guess the compiler returns an garbage value(possibly seen as an uninitialized value). It happens at compile time, why should n't it throw an error.

例如,

   int func1() {
        return; // error
   }

   int func2() {
        // does_not_return_anything
   }

第二FUNC2,应该抛出一个错误,但事实并非如此,有它的一个原因,我的想法是这样的,它可以被看作是一个未初始化的值,所以如果我们需要在第二种情况下抛出错误,那么我们就需要抛出错误,如果值未初始化,说

the second func2, should throw an error, but it does not, Is there a reason for it, my thinking was such that, it can be seen as an uninitialized value, so if we need to throw error in the second case, then we need to throw error, if an value is uninitialized, say

  int i;// error
  int i=6;//okay.

任何想法,或者这是一个重复的问题?我AP preciate你的帮助。

Any thoughts, or is this a duplicate question? I appreciate your help.

推荐答案

在C ++中,例如code有未定义的行为:

In C++, such code has undefined behaviour:

[stmt.return] / 2 ...流动关闭的函数的末尾等于没有值的返回;这会导致不确定的行为在一个返回值的功能。 ...

[stmt.return]/2 ... Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function. ...

大多数编译器将产生code的问题类似的警告。

Most compilers will produce a warning for code similar to that in the question.

C ++标准并没有要求这是一个编译时错误,因为在一般情况下,这将是非常难以正确地确定code是否实际运行关闭该功能的结尾,或者如果函数退出通过异常(或longjmp的或类似的机制)。

The C++ standard does not require this to be a compile time error because in the general case it would be very difficult to correctly determine whether the code actually runs off the end of the function, or if the function exits through an exception (or a longjmp or similar mechanism).

考虑

int func3() {
    func4();
}

如果 FUNC4()抛出,那么这code是完全正常。编译器可能无法看到 FUNC4的定义()(因为单独编译),所以无法知道它是否会抛出与否。

If func4() throws, then this code is totally fine. The compiler might not be able to see the definition of func4() (because of separate compilation), and so cannot know whether it will throw or not.

此外,即使编译器可以证明 FUNC4()不抛,它仍然必须证明, FUNC3()实际上被调用,然后才能合法地拒绝该方案。这种分析要求的整个程序,这与单独的编译不相容的检查,这是不甚至有可能在一般情况下。

Furthermore, even if the compiler can prove that func4() does not throw, it would still have to prove that func3() actually gets called before it could legitimately reject the program. Such analysis requires inspection of the entire program, which is incompatible with separate compilation, and which is not even possible in the general case.

这篇关于如果一个函数没有返回值,有一个有效的返回类型,什么情况下可以为编译器扔垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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