为什么我的函数枚举了可以用 int 表示的所有 10 的幂,但在一台计算机上却不能在另一台计算机上运行?

Why does my function that enumerates all of the powers of 10 that can be represented by an int work on one computer but not the other?

我的代码如下:

void findten ()
    {
        int x = 1, power = 0;
        printf("10^%d, x = %d\n", power++, x);
        while((x*10)/10 == x)
        {
            x *= 10;
            printf("10^%d, x = %d\n", power++, x);
        }
    }

想法是当 x > 10e9 因为最大整数值时循环应该停止。当我第一次 运行 编译它时它工作得很好,并且它继续在我第一次写它的计算机上。我们称这台计算机为 A.

在另一台计算机 B 上,我编译了包含该函数的相同文件,但它不起作用,而是 运行 一个无限循环,其中 x 最终等于 0。我很困惑为什么会这样发生了。

两者的功能确实是一样的

电脑A给我的正确输出:

10^0, x = 1
10^1, x = 10
10^2, x = 100
10^3, x = 1000
10^4, x = 10000
10^5, x = 100000
10^6, x = 1000000
10^7, x = 10000000
10^8, x = 100000000
10^9, x = 1000000000

计算机 B 列出了相同的输出,但随后继续进行并溢出了 int。最终 x = 0 在某个时候,出于我不明白的原因。

问题是有符号整数溢出会导致未定义的行为。因此,如果 x * 10 大于 INT_MAX,x * 10 / 10 == x 就麻烦了。

我假设在您的一台计算机上表示有符号整数的方式在溢出时将 int 包装起来,而另一台计算机则没有。