这是一个示例来说明我的问题,其中涉及一些我无法在此处发布的更复杂的代码。
#include <stdio.h>
int main()
{
int a = 0;
for (int i = 0; i < 3; i++)
{
printf("Hello\n");
a = a + 1000000000;
}
}
该程序在我的平台上包含未定义的行为,因为 a
将在第三次循环时溢出。
这会使整个程序有未定义的行为,还是只有在溢出实际发生之后?编译器是否有可能解决 a
将 溢出,因此它可以声明整个循环未定义,即使它们都发生在溢出之前,也不必费心运行 printfs? p>
(标记为 C 和 C++,即使它们不同,因为如果它们不同,我会对两种语言的答案感兴趣。)
最佳答案
如果您对纯理论答案感兴趣,C++ 标准允许未定义的行为“时间旅行”:
[intro.execution]/5:
A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input. However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation)
因此,如果您的程序包含未定义的行为,那么您的整个程序的行为是未定义的。
关于c++ - 在循环中的什么时候整数溢出成为未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39914788/