在C ++中省略return语句

编程入门 行业动态 更新时间:2024-10-23 11:23:53
本文介绍了在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语句

本文发布于:2023-11-03 15:00:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555418.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   return

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!