问题描述
我刚刚有一些奇怪的行为从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]
例如
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语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!