gpt4 book ai didi

c++ - 比较 -INT_MIN (GCC)

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:58 24 4
gpt4 key购买 nike

谁能解释 GCC-7 编译器的以下行为?

// main.cpp
#include <iostream>

using namespace std;

int main()
{
int a = -2147483648;
int b = -a;

cout << "a == " << dec << a << " == 0x" << hex << a << "\n";
cout << "b == " << dec << b << " == 0x" << hex << b << "\n";

if (a > 0)
cout << "a > 0 // ERROR\n";
else
cout << "a <= 0 // OK\n";

if (b > 0)
cout << "b > 0 // ERROR\n\n";
else
cout << "b <= 0 // OK\n\n";

int aa[] = { -2147483648, 0 };
int bb = -aa[0];

cout << "aa[0] == " << dec << aa[0] << " == 0x" << hex << aa[0] << "\n";
cout << "bb == " << dec << bb << " == 0x" << hex << bb << "\n";

if (aa[0] > 0)
cout << "aa[0] > 0 // ERROR\n";
else
cout << "aa[0] <= 0 // OK\n";

if (bb > 0)
cout << "bb > 0 // ERROR\n\n";
else
cout << "bb <= 0 // OK\n\n";

cin.get();
return 0;
}

没有优化的编译:g++ main.cpp

输出:

a == -2147483648 == 0x80000000
b == -2147483648 == 0x80000000
a <= 0 // OK
b <= 0 // OK

aa[0] == -2147483648 == 0x80000000
bb == -2147483648 == 0x80000000
aa[0] <= 0 // OK
bb <= 0 // OK

优化编译:g++ -O2 main.cpp

输出:

a == -2147483648 == 0x80000000
b == -2147483648 == 0x80000000
a <= 0 // OK
b <= 0 // OK

aa[0] == -2147483648 == 0x80000000
bb == -2147483648 == 0x80000000
aa[0] <= 0 // OK
bb > 0 // ERROR

这是未定义的行为还是编译器错误?

GCC版本:gcc(Ubuntu 7.3.0-27ubuntu1~18.04)7.3.0

最佳答案

这是未定义的行为。大概在你的机器上 int 是 32 位的,其范围是 -21474836482147483647。尝试否定 -2147483648 会导致溢出(不是 Stack Overflow :P),这是未定义的行为(定义了无符号溢出,但没有定义有符号溢出。)因此编译器可以做任何它喜欢的事情。

关于c++ - 比较 -INT_MIN (GCC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52679742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com