我刚刚有一些奇怪的行为从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语句
发布评论