I am wondering what is the most portable way to check if the correct shift is arithmetic when working for signed types (e.g. -2 >> 1 is -1 ) at compile time.
My idea is to check this somehow at compile time and be able to detect it, so I can compile different versions of the function (depending on whether the >> operator is really an arithmetic shift or not).
After reading the topic Checking that the right shift / C / C ++ shift is arithmetic for a particular compiler? I came up with the idea of ββinitializing the flag
static const bool is_arithmetic_rs = (((signed int)-1)>>1) == ((signed int)-1));
and test it at runtime as follows:
if (is_arithmetic_rs) { // some fast algorithm using arithmetic right shifts (using >> operator) } else { // the same algorithm without arithmetic right shifts (much slower) }
However, I would like to avoid this branching, if possible every time. For simplicity, suppose I want to implement a portable arithmetic shift to the right; if I had to check this every time a function is called, it will have a huge impact on performance, so I would like to do this at compile time, if possible.
If there is no portable way to do this check, is there a way to do this by checking the best results, for example, checking with ifdefs for a specific compiler / platform?
source share