r/C_Programming • • 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

56 comments sorted by

View all comments

Show parent comment

2

u/TheThiefMaster Oct 16 '26

Unsigned right shift (logical shift) behaves differently to signed right shift (99.9% arithmetic right shift) - that's not a workaround if that's what you want.

Plus - I'm pretty sure casting to/from unsigned is also implementation defined for negative numbers

0

u/pskocik Oct 16 '26

Yeah. Doesn't quite work for signed right shifts. But for left shifts it does. Doing arithmetic shifts on signed right shifts is the sensible thing to do. I once played with detecting it with #if and doing some complicated workaround otherwise but it might make sense to just rely on the C++ behavior here and #error if it's not supported.

1

u/TheThiefMaster Oct 16 '26

For left shifts in C you still get undefined behaviour if you shift into what casts to a negative value, and for values that remain positive there's no change.