比较-INT_MIN(GCC)

时间:2018-10-06 13:51:32

标签: c++

有人可以解释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

1 个答案:

答案 0 :(得分:2)

这是未定义的行为。大概在您的计算机上int是32位,范围是-21474836482147483647。试图取反-2147483648会导致溢出(不是Stack Overflow:P),这是未定义的行为(定义了未签名的溢出,但不是用于签名的。)因此,编译器可以执行其喜欢的任何事情。