如何沉默“最后一条语句应该返回一个值”警告? [英] How to silence 'The last statement should return a value' warning?

查看:147
本文介绍了如何沉默“最后一条语句应该返回一个值”警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Sun Studio 12.1打印警告

Sun Studio 12.1 prints the warning

Warning: The last statement should return a value.

经常出现这样的功能:

int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}

很清楚,我们不需要在结束时返回值功能。我不犹豫地插入像

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

// Silence a compiler warning
return 42;

在这样一个函数的结尾,因为它是死代码。对于更复杂的返回类型,可能实际上难以构造一个明智的伪造值。

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

建议的方法是什么?

What is the recommended way to silence such a warning?

推荐答案

你可以在函数中重组代码(希望更符合逻辑),正常路径发生在

Can you reorganize the code in the function in such a way (hopefully more logical as well) that the normal path happens at the end of the function so that a return can be used, and the exceptional path happens earlier, NOT as the last statement?

编辑:如果重新组织函数真正,那么可以使用返回, >没有意义,你可以随时放一个 return 0; 和一个注释。

If reorganizing the function really doesn't make sense, you can always just put a dummy return 0; with a comment. It's better to squelch the warning that way than more globally.

如果你真的想静静地警告这个警告,你可以使用 #pragma error_messages off,wnoretvalue)但是请注意,警告真的在大多数时候是有用的,所以我绝对不建议关闭它。您可以使用 c> c>版本的pragma重新启用该函数后的警告,但如果函数已内联,编译器仍会发出警告。如果你把函数放在自己的源文件中,并使用pragma,应该相对安全地注销警告,因为它不会影响其他翻译单元。

If you really want to quiet the warning permanently, you can use #pragma error_messages (off, wnoretvalue) but note that the warning really is useful most of the time so I absolutely don't suggest turning it off. You can use the on version of the pragma to re-enable the warning after the function, but the compiler will still emit the warning if your function is ever inlined. If you put the function in its own source file and use the pragma that should shush the warning relatively safely though, since it can't affect other translation units.

古怪的可能性是切换到g ++。除非你正在编译SPARC,g ++实际上可能会产生比Sun studio更好的代码。

Another really wacky possibility is to switch to g++. Unless you're compiling for SPARC g++ may actually generate better code than Sun studio.

这篇关于如何沉默“最后一条语句应该返回一个值”警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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