4

编译器优化有时会跳过对某些没有结果的语句的评估。但是,这也适用于逗号运算符吗?

以下代码在ideone上运行没有任何错误,但我预计它会崩溃。

#include <iostream>

int main() {
    int x = (1/0, 2);
    std::cout << x << std::endl;
}

如果我将语句更改为,程序确实会崩溃int x = 1/0;

4

1 回答 1

8

编译器优化使用As-if 规则

好像规则

允许任何和所有不改变程序可观察行为的代码转换

所以是的,编译器可以对此进行优化。检查以下修改后的示例

#include <iostream>

int main() 
{
    int y = 1;
    int x = (y=1/0, 2);
    std::cout << x << std::endl;
    //std::cout << y << std::endl;
} 

注释最后一行可以正确编译并执行此代码,而取消注释它会为您提供预期的未定义行为。

As @jogojapan correctly points out,
It is important to note that compiler optimizations are not guaranteed by the standard and divide by zero is a Undefined behavior. So this code does have an undefined behavior. Whether the observable behavior is because of compiler optimizing out the divide by zero or due to undefined behavior we can never know. Technically, it is Undefined behavior all the same.

于 2013-02-21T06:14:35.350 回答