LeetCode 上奇怪的编译器行为

Weird compiler behavior on LeetCode

本文关键字:编译器 LeetCode      更新时间:2024-09-29

我正在解决LeetCode问题: 7.反向整数,出于测试目的,我打印了一些值(long long x2long long x3)。在这里,xRough的值被分配给x2,如果xxRough为负,则x3,否则将附加一个未定义的值。但是,LeetCode 编译器xRough的值分配给x2x3即使x为正(而不是分配未定义的值)。我在不同的编译器上测试了这段代码,当x为正时,它们给出了未定义的x2x3值。但是LeetCode编译器给出了错误的结果。

这不是LeetCode编译器的错误或奇怪的行为,还是我在这里遗漏了一些点?

class Solution {
public:
int reverse(int x) {
long long x2, x3;
long long xRough = (long long) x;

if (xRough < 0){
x2 = x3 = (-1) * xRough;
}

cout<<x2<<" "<<x3<<" "<<xRough<<endl;

return 0;
}
};

我也接受了编译器的这种奇怪行为。接受的代码是:

class Solution {
public:
int reverse(int x) {
long long flag = 0, y, x2, x3, xRough = (long long) x;
long long theNum = 0, i = 1;

if (xRough < 0)
x2 = x3 = std::abs(xRough);

while (1) {
x2 = x2 / 10;
i = i * 10;
if (x2 == 0)
break;
}
i = i / 10;
while (1) {
y = x3 % 10;
x3 = x3 / 10;
theNum = theNum + y * i;
i = i / 10;
if (x3 == 0)
break;
}
if (x < 0) {
if (theNum > std::pow(2, 31))
return 0;
else
return (-1) * theNum;
} else {
if (theNum > (std::pow(2, 31) - 1))
return 0;
else
return theNum;
}
}
};

在你的函数中:

class Solution {
public:
int reverse(int x) {
long long x2, x3;
long long xRough = (long long) x;

if (xRough < 0){
x2 = x3 = (-1) * xRough;
}

cout<<x2<<" "<<x3<<" "<<xRough<<endl;

return 0;
}
};

必须区分两种情况。要么xRough < 0true,要么false

当它被truex2将得到一个分配的值,一切都按您的预期工作。

当它被false时,代码会尝试打印x2x3的值,但它们没有初始化。它们具有不确定的值。如果不调用未定义的beahvior,则无法对不确定的值执行任何操作。

函数定义输出的唯一方法是xRough < 0true时。当它为假时,输出可以是任何内容。因此,编译器允许完全忽略xRough < 0false的情况。这就是编译器的构建目的,这就是为什么它们擅长优化代码,它们可以消除代码中从未被采用的路径(或者可能永远不会被采用,因为结果无论如何都是未定义的)。