为什么编译器不警告你,如果有可能的未定义行为? [英] Why doesn't the compiler warn you if there is possible Undefined Behaviour?

查看:199
本文介绍了为什么编译器不警告你,如果有可能的未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读着名的未定义的行为可能会导致时间旅行 post并注意到这部分:

I was reading the famous Undefined Behavior can cause time travel post and noticed this part:


首先,你可能注意到循环中的一个错误
控制。结果是,函数在放弃之前读取一个超过
表数组的末尾。经典的编译器不会特别注意
。它只是生成读取
out-of-bound数组元素的代码(尽管这样做是违反语言规则的
),并且如果$ b $

First of all, you might notice the off-by-one error in the loop control. The result is that the function reads one past the end of the table array before giving up. A classical compiler wouldn't particularly care. It would just generate the code to read the out-of-bounds array element (despite the fact that doing so is a violation of the language rules), and it would return true if the memory one past the end of the array happened to match.

另一方面,后经典编译器可能会在分析后执行

A post-classical compiler, on the other hand, might perform the following analysis:

在循环的前四次,函数可能返回true。

The first four times through the loop, the function might return true.

,代码执行未定义的行为。因为未定义的行为让我做任何我想要的,我可以完全忽略
的情况下,继续假设我永远不是4.(如果
假设违反,那么不可预测的事情发生,但
,没关系,因为未定义的行为允许我
不可预测。

post(更新的)编译器可以在编译时对未定义行为进行操作,这意味着在某些情况下它完全能够发现未定义行为。而不是让恶魔飞出你的鼻子或产生龙通过消除UB代码或只是转换它,因为它允许为什么编译器不发出警告,这可能是不是打算?

According to this post the (newer) compiler can already act upon Undefined Behavior at compile-time which means that it is perfectly capable to spot Undefined Behavior in some cases. Instead of letting demons fly out of your nose or spawning dragons by eliminating the UB code or just transforming it because it's allowed to why doesn't the compiler just emit a warning that this is probably not intended?

推荐答案

编译器的工作是将代码从高级语言编译到低级语言。如果你得到一个描述性的错误或警告消息,它是时候感谢编译器,它为你做了额外的工作。要获取必需的警告,请使用一些静态代码分析工具。

The work of compiler is to compile the code from high level language to lower level. If you get a descriptive error or warning message, it is the time to thanks to the compiler that it did extra job for you. For getting the required warning, use some static code analysis tool.

在规范中没有明确定义的任何内容都是未定义的,因此无法准备未定义行为的完整列表。

And anything not well defined in the spec is undefined, and it is not possible to prepare a comprehensive list of undefined behaviour. Emitting warning on all such behaviours may not be possible.

实际上,在许多情况下,编译器会通过正确的警告标志(例如)警告未定义的行为, -W -Wall -Wextra -O2 。 (使用 -O2 这样的优化标记会对代码进行回归分析,并可能产生更多警告)

Practically, in many cases, compilers do warn about undefined behaviours specially with proper warning flags like -W -Wall -Wextra -O2 on gcc. (with optimization flags like -O2 compiler would do regress analysis of code and may generate more warning)

这篇关于为什么编译器不警告你,如果有可能的未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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