我从Strawberry Perl的Windows版本的g++中获得了一些奇怪的行为。它使我省略了退货声明。

我有一个成员函数,该函数返回由两个指针组成的结构,称为boundTag:

struct boundTag Box::getBound(int side) {
    struct boundTag retBoundTag;
    retBoundTag.box = this;
    switch (side)
    {
        // set retBoundTag.bound based on value of "side"
    }
}

此函数给了我一些不好的输出,我发现它没有return语句。我原本打算返回retBoundTag,但是却忘了实际编写return语句。添加return retBoundTag;后,一切都很好。

但是我已经测试了此功能,并从中获得了正确的boundTag输出。即使现在,当我删除return语句时,g++也会在没有警告的情况下对其进行编译。 WTF?它是否猜测要返回retBoundTag

最佳答案

return函数[non-void除外]中省略main()语句,并在代码中使用返回值将调用Undefined Behaviour

ISO C++-98 [第6.6.3/2节]



例如

int func()
{
    int a=10;
    //do something with 'a'
    //oops no return statement
}


int main()
{
     int p=func();
     //using p is dangerous now
     //return statement is optional here
}

通常,g++提供了warning: control reaches end of non-void function。尝试使用-Wall选项进行编译。

关于c++ - 在C++中省略return语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3402178/

10-14 17:05
查看更多