Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

integer comparision; difference in behavior between Clang and GCC 12

I'm seeing a strange (to me) difference in behavior between Clang and GCC when comparing an integer with its negation. Also, pre-v12 GCC behaves like Clang.

Code is below, but also here's a live link on godbolt.org.

int32_t x = 0x80000000U;
cout << " x: " << x << endl;
cout << "-x: " << -x << endl;
if ( x == -x) {
 cout << "equal" << endl;
} else {
 cout << "NOT equal" << endl;
}

For GCC versions before 12, and for modern Clang, this prints "equal"

For GCC 12+, this prints "NOT equal".

My question is: why?

It does not seem to be a bug, since all GCC versions from 12 on have this behavior. But it is clearly a change from historical behavior.

Is there a reason behind this change? What is actually going on in this code, in the two different cases?

My only guess is that somehow GCC is promoting x to a larger type, since 0x80000000 does not fit in int32_t, and using that for the comparison. But by what logic?

Note: even adding a int32_t(-x) cast inside the comparison does not change the behavior.

Answer*

Draft saved
Draft discarded
Cancel
3
  • 2
    Actually, unsigned to signed conversions like this became well-defined in C++20, and are now guaranteed to result in "the unique value of the destination type that is congruent to the source integer modulo 2^N , where N is the width of the destination type" (which is what you would normally expect). This is because, starting from C++20, integers are required to use two's complement for the representation Commented Aug 29, 2025 at 19:55
  • 2
    Signed overflow due to arithmetic is, of course, still undefined behavior Commented Aug 29, 2025 at 19:55
  • @shananton Ah thanks — I updated it to make note of C++20. Commented Aug 30, 2025 at 20:02

lang-cpp

AltStyle によって変換されたページ (->オリジナル) /