在C ++中省略return语句 [英] Omitting return statement in C++

查看:258
本文介绍了在C ++中省略return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚有一些奇怪的行为从g ++的Windows版本,我得到了草莓Perl。它允许我省略一个返回语句。

I just had some weird behavior from a version of g++ for Windows that I got with Strawberry Perl. It allowed me to omit a return statement.

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

I have a member function that returns a structure consisting of two pointers, called a boundTag:

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

这个函数给了我一些错误的输出,我发现它没有返回语句。我想要返回 retBoundTag ,但忘了实际写return语句。一旦我添加返回retBoundTag; 一切都很好。

This function gave me some bad output, and I discovered that it had no return statement. I had meant to return retBoundTag but forgot to actually write the return statement. Once I added return retBoundTag; everything was fine.

但我已经测试了这个函数, $ c> boundTag 从它输出。即使现在,当我删除return语句,g ++编译它没有警告。 WTF?是否猜到要返回 retBoundTag

But I had tested this function and gotten correct boundTag output from it. Even now, when I remove the return statement, g++ compiles it without warning. WTF? Does it guess to return retBoundTag?

推荐答案

非void 函数中的$ c> return 语句[除 main()并使用您代码中的返回值调用未定义的行为

Omitting the return statement in a non-void function [Except main()] and using the returned value in your code invokes Undefined Behaviour.

ISO C ++ - 98 [Section 6.6.3 / 2]

ISO C++-98[Section 6.6.3/2]


可以使用带有表达式的return语句
函数返回值;该表达式的值是
返回给函数的调用者。如果需要,表达式
隐式转换为函数的返回类型,
出现在该函数中。返回语句可以包括构造和复制
临时对象( class.temporary )。 结束
函数的流程相当于没有值的返回;这会在值返回函数中产生
未定义的行为

例如

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 
}


b $ b

通常,g ++给出一个警告:控制到达非void函数结束。尝试使用 -Wall 选项进行编译。

Generally g++ gives a warning: control reaches end of non-void function. Try compiling with -Wall option.

这篇关于在C ++中省略return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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