Search code examples
cbit-manipulationundefined-behaviorubsan

UBSAN reports: -875 << 7 as undefined behaviour


Simple code snippet:

#define FOO 7
int bar = -875;
bar <<= FOO;

This is being reported by UBSAN as UB.

My understanding is that -875 << 7 is just -(875<<7) and there is no overflow.

So, is there a real problem here?


Solution

  • Your understanding is incorrect.

    Firstly you used bar <<= FOO syntax. This explicitly shifts bar and bar is negative. Left-shifting of negative values produces undefined behavior in C. There's no way bar <<= FOO can be interpreted as -(875<<7).

    Secondly, concerning -875 << 7 in terms of operator priority: unary operators always have higher priority than binary ones, which means that -875 << 7 is (-875) << 7 and not -(875 << 7). And, again, left-shifting of negative values produces undefined behavior in C.