c++ - 如果可能存在未定义行为,为什么编译器不警告您?

标签 c++ undefined-behavior

我正在阅读著名的 Undefined Behavior can cause time travel发布并注意到这部分:

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:

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

When i is 4, the code performs undefined behavior. Since undefined behavior lets me do anything I want, I can totally ignore that case and proceed on the assumption that i is never 4. (If the assumption is violated, then something unpredictable happens, but that's okay, because undefined behavior grants me permission to be unpredictable.)

根据这篇文章,(较新的)编译器已经可以在编译时对未定义的行为采取行动,这意味着它在某些情况下完全能够发现未定义的行为。而不是通过消除 UB 代码或只是转换它来让恶魔飞出你的 Nose 或产生龙,因为它是允许的,为什么编译器不只是发出这可能不是故意的警告?

最佳答案

编译器的工作是将代码从高级语言编译到低级语言。如果您收到描述性错误或警告消息,是时候感谢编译器为您做了额外的工作。要获得所需的警告,请使用一些 static code analysis工具。

并且规范中没有明确定义的任何内容都是未定义的,并且不可能准备一份完整的未定义行为列表。可能无法对所有此类行为发出警告。

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

关于c++ - 如果可能存在未定义行为,为什么编译器不警告您?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942101/

相关文章:

c++ - 使用按位运算创建 char 字符时出现问题

C++ ofstream 写入在 Windows 下不起作用。在 Linux 下工作正常

c - 在 C 中没有参数的 printf() 可以正常编译。如何?

c++ - 为什么这个 for 循环不停止?

c++ - 添加到std::vector时,类字段的行为异常

c++ - DrawText 和文本裁剪

c++ - 静态变量和 new() 之间的单例

c++ - 如何使用 vector 创建随机 double 矩阵?

c++ - 未定义的行为和顺序点

c++ - 来自 const_iterator 取消引用的赋值会导致未定义的行为吗?