Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why worry about 'undefined behavior' in >> of signed type?

My question is related to this one and will contain few questions.

For me the most obvious (means I would use it in my code) solution to above problem is just this:

uint8_t x = some value;
x = (int8_t)x >> 7;

Yes, yes I hear you all .... undefined behavior and this is why I've not posted my 'solution'.

I have a feeling (maybe it is only my sick mind) that term 'undefined behavior' is overused on SO just to justify downvoting someone if question is tagged c/c++.

So - let's (for a while) put aside C/C++ standards and think about everyday life/programming, real compiler implementations and code they generate for contemporary hardware.

Taking into account the following:

  • As far as I remember all the hardware I had encountered had distinct instructions for arithmetic and logical shift.
  • All compilers that I know translate >> into arithmetic shift for signed types and logical shift for unsigned types.
  • I cannot recall any compiler ever emitting div-like low level instruction when >> was used in c/c++ code (and we are not talking about operator overloading here).
  • All the hardware I know use U2.

So ... is there anything (any contemporary compiler, hardware) that behaves differently than mentioned above? Put simply should I ever be worried about right shifting signed value not being translated to arithmetic shift?

My 'solution' compiles to just one low level instruction on many platforms while others require multiple low level instructions. What would you use in your code?

Truth please ;-)

like image 972
Artur Avatar asked Dec 18 '13 21:12

Artur


1 Answers

Why worry about 'undefined behavior' in >> of signed type?

Because it doesn't really matter how well defined any particular undefined behaviour is now; the point is that it may break at any point in the future. You're relying on a side-effect that may be optimized (or un-optimized) away at any point for any reason or no reason.

Also, I don't want to have to ask somebody with detailed knowledge of many different compiler's implementations before I use something I shouldn't use in the first place, so I skip it.

like image 138
meagar Avatar answered Sep 23 '22 22:09

meagar