c++ - 在循环中的什么时候整数溢出成为未定义的行为?

标签 c++ c undefined-behavior integer-overflow

这是一个示例来说明我的问题,其中涉及一些我无法在此处发布的更复杂的代码。

#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/

相关文章:

c - 是否有一种故障安全方法来确定 C 中指针的对齐/尾随位?

常见的 lisp、CFFI 和实例化 c 结构

c - 逻辑错误行文件在哪里

c++ - 加载 DLL 阻塞 UI 线程

c++ - 如何找到一棵树的大小和高度?

c - 使用bash脚本查找C程序的方法和方法调用

c++ - 为什么与 printf 未定义行为中的转换说明符不匹配的参数?

c++ - “is not required” ==未定义行为?

c++ - 使用 StereoBM 时视差图中的黑色列

c++ - 使用 ffmpeg 将图像写入 RTP