LeetCode 上奇怪的编译器行为
Weird compiler behavior on LeetCode
我正在解决LeetCode问题: 7.反向整数,出于测试目的,我打印了一些值(long long x2
和long long x3
)。在这里,xRough
的值被分配给x2
,如果x
或xRough
为负,则x3
,否则将附加一个未定义的值。但是,LeetCode 编译器将xRough
的值分配给x2
并x3
即使x
为正(而不是分配未定义的值)。我在不同的编译器上测试了这段代码,当x
为正时,它们给出了未定义的x2
和x3
值。但是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 < 0
true
,要么false
。
当它被true
x2
将得到一个分配的值,一切都按您的预期工作。
当它被false
时,代码会尝试打印x2
和x3
的值,但它们没有初始化。它们具有不确定的值。如果不调用未定义的beahvior,则无法对不确定的值执行任何操作。
函数定义输出的唯一方法是xRough < 0
true
时。当它为假时,输出可以是任何内容。因此,编译器允许完全忽略xRough < 0
false
的情况。这就是编译器的构建目的,这就是为什么它们擅长优化代码,它们可以消除代码中从未被采用的路径(或者可能永远不会被采用,因为结果无论如何都是未定义的)。
相关文章:
- C/C++编译器通常会删除重复的库吗
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- Win32编译器选项和内存分配
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++,我收到一个无法理解的编译器错误
- 在线编译器中的分段C++没有打印消息
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- C/C++预处理器是否可以检测一些编译器选项
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 我需要知道编译器如何在cpp中使用析构函数
- 编译器如何区分std::vector的构造函数
- CLANG 编译器 说:变量"PTR"可能未初始化
- 告诉c++编译器该参数没有别名
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么所有C++编译器都会崩溃或挂起此代码
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?