gpt4 book ai didi

c - 关于未定义的行为

转载 作者:太空狗 更新时间:2023-10-29 16:42:52 25 4
gpt4 key购买 nike

一般来说,UB被认为是必须要避免的东西,目前的C标准本身在附录J中就列举了相当多的例子。

但是,在某些情况下,除了牺牲可移植性外,我认为利用 UB 没有任何坏处。

考虑以下定义:

int a = INT_MAX + 1;

评估此表达式会导致 UB。但是,如果我的程序打算在 32 位 CPU 上运行,并使用二进制补码表示值的模运算,我倾向于相信我可以预测结果。

在我看来,UB 有时只是 C 标准告诉我的方式:“我希望你知道你在做什么,因为我们无法保证会发生什么。”

因此我的问题是:有时依赖机器相关行为是否安全,即使 C 标准认为它调用 UB,或者无论情况如何,“UB”真的应该避免吗?

最佳答案

,除非您还保持编译器相同并且您的编译器文档定义了其他未定义的行为。

未定义的行为意味着您的编译器可以出于任何原因忽略您的代码,使您不认为的事情成真应该是。
有时这是为了优化,sometimes it's because of architecture restrictions like this .


我建议你阅读 this ,它解决了您的确切示例。摘录:

Signed integer overflow:

If arithmetic on an int type (for example) overflows, the result is undefined. One example is that INT_MAX + 1 is not guaranteed to be INT_MIN. This behavior enables certain classes of optimizations that are important for some code.

For example, knowing that INT_MAX + 1 is undefined allows optimizing X + 1 > X to true. Knowing the multiplication "cannot" overflow (because doing so would be undefined) allows optimizing X * 2 / 2 to X. While these may seem trivial, these sorts of things are commonly exposed by inlining and macro expansion. A more important optimization that this allows is for <= loops like this:

for (i = 0; i <= N; ++i) { ... }

In this loop, the compiler can assume that the loop will iterate exactly N + 1 times if i is undefined on overflow, which allows a broad range of loop optimizations to kick in. On the other hand, if the variable is defined to wrap around on overflow, then the compiler must assume that the loop is possibly infinite (which happens if N is INT_MAX) - which then disables these important loop optimizations. This particularly affects 64-bit platforms since so much code uses int as induction variables.

关于c - 关于未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6103822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com