r/C_Programming • u/am_Snowie • Oct 16 '26
Question is doing ~INT_MAX undefined behavior?
basically the title, i think producing INT_MIN by doing 1 << 31 is UB, so i thought of doing ~INT_MAX, but i am not sure if it's UB. sorry if it's dumb.
47
Upvotes
View all comments
2
u/TheThiefMaster Oct 16 '26 edited Oct 16 '26
C++ made this explicitly legal, even before it standardised on 2s complement, by defining the behaviour as the same as an unsigned->signed conversion as long as the shift would have fit in the unsigned version of the type (which IIRC is an implementation-defined conversion, rather than undefined, before C++20 forced 2s complement and made it defined).
By my reading it's UB in older C and is still UB in C23, however doing
(signed)(1u << 31)instead might actually be legal?(assuming int is 32-bit, of course)