对于不返回void的C ++函数,返回语句是否是强制性的? [英] Is a return statement mandatory for C++ functions that do not return void?
问题描述
我使用gcc(MinGW)并设置了-pedantic标志。
2:
离开函数的末尾等效于没有值的返回;这会导致在一个值返回函数中的未定义的行为。
所以它取决于你的定义的强制性。 是否到了?不是。但是如果你想你的程序有明确的行为,是的。*
* main
是一个例外,见§3.6.1/ 5。如果控制到达 main
的结尾而没有返回
,它将具有 return 0;
。
My Herb Schildt book on C++ says: "... In C++, if a function is declared as returning a value, it must return a value." However, if I write a function with a non-void return type and do not return anything, the compiler issues a warning instead of an error: "Control reaches end of non-void function."
I use gcc (MinGW) and have set the -pedantic flag.
§6.6.3/2:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
So it depends on your definition of mandatory. Do you have to? No. But if you want your program to have well-defined behavior, yes.*
*main
is an exception, see §3.6.1/5. If control reaches the end of main
without a return
, it will have the effect of return 0;
.
这篇关于对于不返回void的C ++函数,返回语句是否是强制性的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!