对于不返回void的C ++函数,返回语句是否是强制性的? [英] Is a return statement mandatory for C++ functions that do not return void?

查看:226
本文介绍了对于不返回void的C ++函数,返回语句是否是强制性的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Herb Schildt在C ++上的书说:...在C ++中,如果一个函数声明为返回一个值,它必须返回一个值。但是,如果我写一个非void返回类型的函数并且不返回任何东西,编译器会发出一个警告,而不是一个错误:控制到达非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屋!

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