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

3

u/Iksfen Oct 16 '26

Thanks for educating. Didn't know that distinction existed

1

u/am_Snowie Oct 16 '26

yeah arithmetic shifting is implementation defined irrc.

1

u/pskocik Oct 16 '26

Right-shifting negatives is implementation-defined (probably an arithmetic shift). Left-shifting negatives or left-shifting signed positives too into and beyond the sign bit is UB https://port70.net/~nsz/c/c11/n1570.html#6.5.7

0

u/TheThiefMaster Oct 16 '26

Note that C++ defines it now - so for simplicity a dual C/C++ compiler probably sets the C "implementation defined" to the C++ rules - which is an arithmetic right shift.

A platform that does anything else is likely to be extremely esoteric

1

u/pskocik Oct 16 '26

You raise a good point but I don't like relying on compilers defining Undefined Behavior so I just tend to work around it by casting to unsigned and back. It's a simple workaround that leaves me legally covered.

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.