为什么“不是所有控制路径都返回值”是警告,而不是错误? [英] Why "not all control paths return a value" is warning and not an error?

查看:174
本文介绍了为什么“不是所有控制路径都返回值”是警告,而不是错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图回答问题。如接受的答案所建议的,该代码的问题是并非所有控制路径都返回值。我试过这个代码在VC9编译器,它给了我一个警告。我的问题是为什么只是一个警告,而不是错误?另外,如果不返回值的路径被执行,函数将返回什么(它必须返回一些东西)?

I was trying to answer this question. As suggested by the accepted answer, the problem with that code is that not all control paths are returning a value. I tried this code on the VC9 compiler and it gave me a warning about the same. My question is why is just a warning and not an error? Also, in case the path which doesn't return a value gets executed, what will be returned by the function (It has to return something) ? Is it just whatever is there on top of the stack or is the dreaded undefined behavior again?

推荐答案

无法从堆栈中返回一个值具有非<:code> void 返回类型的函数会导致未定义的行为,但不是语义错误。

Failing to return a value from a function that has a non-void return type results in undefined behaviour, but is not a semantic error.

根据我可以确定的原因很大程度上是历史的。

The reason for this, as far as I can determine, is largely historical.

C最初没有 void 和隐含 int 意味着大多数函数返回一个 int ,除非明确声明返回其他东西,即使没有意图使用返回值。

C originally didn't have void and implicit int meant that most functions returned an int unless explicitly declared to return something else even if there was no intention to use the return value.

这意味着很多函数返回一个int,但没有显式地设置返回值,但是没关系,因为调用者永远不会使用

This means that a lot of functions returned an int but without explicitly setting a return value, but that was OK becase the callers would never use the return value for these functions.

有些函数返回一个值,但使用隐式 int ,因为 int 是一个合适的返回类型。

Some functions did return a value, but used the implicit int because int was a suitable return type.

这意味着pre - void 代码有很多函数名义上返回 int ,但可以声明返回 void 和许多其他函数应该返回一个 int ,没有明确的方法来区分。在任何阶段对所有非 - void 函数的所有代码路径执行 return 会破坏旧代码。

This means that pre-void code had lots of functions which nominally returned int but which could be declared to return void and lots of other functions that should return an int with no clear way to tell the difference. Enforcing return on all code paths of all non-void functions at any stage would break legacy code.

还有一个论点,一个函数中的一些代码路径可能无法访问,但这可能不容易从简单的静态分析中确定,为什么强制执行一个不必要的 return

There is also the argument that some code paths in a function may be unreachable but this may not be easy to determine from a simple static analysis so why enforce an unnecessary return?

这篇关于为什么“不是所有控制路径都返回值”是警告,而不是错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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