【问题标题】:Is there a GCC extension for implict return values?是否有隐含返回值的 GCC 扩展?
【发布时间】:2011-10-20 21:52:12
【问题描述】:

我曾经并且已经更正了类似以下代码的内容:

class SomeClass {
public:
    static int AdjustValue(float input);
    static int DoSomethingWithAdjustedValue(int adjustedInput);
    static int DoSomethingWithNormalValue(float input) {
        DoSomethingWithAdjustedValue(AdjustValue(input);}
};

所以DoSomethingWithNormalValue 显然缺少return,但 GCC 并没有为它生成错误或警告。我打电话给DoSomethingWithNormalValue 的地方得到了正确的返回码。我可以想到两种解释:

  1. GCC 中有一些扩展可以识别内联函数,这些函数包装了其他函数并传递返回值。

  2. 由于未定义行为的幸运/不幸表现以及 GCC 中阻止任何错误或警告的错误,返回代码被传递。

我觉得这些都不太可能。这是怎么回事?

【问题讨论】:

  • 提高警告级别。它会警告你。
  • 当您缺少return 语句时,什么是“正确的返回码”?

标签: c++ gcc android-ndk undefined-behavior


【解决方案1】:

C++ 不需要对此进行诊断,但它是未定义的行为。

您获得正确值的原因是因为DoSomethingWithAdjustedValue 将其返回值放在返回值所在的位置,然后DoSomethingWithNormalValue 不会弄乱任何返回值,因此任何在它们之后寻找返回值的东西调用DoSomethingWithNormalValue会看到DoSomethingWithAdjustedValue返回的值。

【讨论】:

    【解决方案2】:

    尝试:

    > g++ xa1.cpp -Wall
    xa1.cpp: In static member function ‘static int SomeClass::DoSomethingWithNormalValue(float)’:
    xa1.cpp:8: warning: no return statement in function returning non-void
    xa1.cpp:8: warning: control reaches end of non-void function
    

    由于未定义行为的幸运/不幸表现以及 GCC 中阻止任何错误或警告的错误,返回代码被传递。

    我想你会发现这就是发生的事情。
    从技术上讲,这是未定义的行为。

    【讨论】:

    • 如果这是在 x86 上,他可能正在读取 eax 的旧值,如果没有被覆盖,幸运的是它会保存前一个函数的返回码。
    • 这是最糟糕的事情,我可以发誓我之前已经看到“控制到达非无效函数的结尾”弹出。但我只是仔细检查了我的构建设置,你是对的。哇!
    猜你喜欢
    • 2015-12-19
    • 2016-04-22
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多