有没有办法让 gcc 或 clang 对缺少的“else”发出警告?
如果我没有处理每个 if 语句的 else 条件,我想让编译器警告我。这是否存在于 clang 或 gcc 中?
需要澄清的是,我并不想在我的所有源代码中启用此功能。然而,有时对于整个文件或大段代码,我根本无法不仔细考虑其他每个块的设计。所以,我想,我真的在寻找一个可以打开和关闭的编译指示,以启用和禁用数千行非常重要的代码。
将其想象为自动代码审查或静态分析工具。
说编译器不能这样做是因为它是合法的……在实践中这不是问题。我见过的每个 C/C++ 编译器都会很乐意针对语法和语义上完全有效的代码发出大量警告。 (例如在 gcc 中,-Wunused-value、-Wunused-label、-Wunreachable-code 等...)
I'd like to have the compiler warn me if I'm not handling every if statement's else condition. Does this exist in either clang or gcc?
To clarify, I'm not trying to have this be on for all of my source code. However, there are sometimes entire files or large swaths of code for which I simply cannot afford to not think hard about every single else block, by design. So, I suppose, I'm really looking for a pragma I can turn on and off to enable and disable this for a few thousands of lines of very important code.
Imagine it as an automated code review, or static analysis tool.
To say that the compiler can't do it because it's legal is ... not a problem in practice. Every C/C++ compiler I've ever seen will gladly emit plenty of warnings against code that is perfectly syntactically and semantically valid. (For example in gcc, -Wunused-value, -Wunused-label, -Wunreachable-code, etc...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您真的想要这个,我可能建议下载Cppcheck并为此添加检查。 Cppcheck 执行简单的基于文本的匹配来检查规则集。对于缺少的
else
子句发出警告是相当简单的。我在
missing-else
分支中实现了“missing else”的原型检查:https://github.com/ghewgill/cppcheck/tree/missing-else。它通过了自己的测试,但由于新的意外样式警告(在其他合法代码上)而导致许多其他测试失败。If you really want this, I might suggest downloading Cppcheck and adding a check for this. Cppcheck does simple kinds of text-based matching to check against a rule set. It would be reasonably straightforward to warn for a missing
else
clause.I implemented a prototype check for "missing else" in the
missing-else
branch here: https://github.com/ghewgill/cppcheck/tree/missing-else. This passes its own test but fails a lot of other tests because of the new unexpected style warning (on otherwise legitimate code).编译器根本不能,一个简单的
if()
就是一个有效的条件语句。编译器警告可能的语义错误,它们并不意味着具有/提供调试设施。
要获得此类功能,您必须依赖一些专门为此目的而设计的代码分析工具。
A compiler simply cannot, a simple
if()
is a valid conditional statement.Compilers warn for possible semantic mistakes, they are not meant to have/provide debugging facilities.
To get such functionalities you will have to rely on some code analysis tools which are specifically made for the purpose.
恐怕这样的检查只会带来大量警告,因为很多代码不使用 else 子句。但如果你只是想检查你的代码,你可以使用这些小宏:
然后你就可以像这样编写你的代码:
当然这是一个坏主意。
Im afraid a check like that would just bring up a mountain of warnings, since so much code doesn't use an else clause. But if you just want to check your code, you could use these little macros:
Then you would just write your code like this:
Of course this is a bad idea.