I am wondering what is the most portable way of checking whether right shift is arithmetic when operating for on signed types (e.g. whether -2 >> 1
is -1
) at compile-time.
My idea is to check this somehow on compile time and be able to detect this, so I can compile different versions of the function (depending whether the operator >>
is really arithmetic shift or not).
By reading the topic Verifying that C / C++ signed right shift is arithmetic for a particular compiler? I came to the idea to initialize a flag
static const bool is_arithmetic_rs = (((signed int)-1)>>1) == ((signed int)-1));
and to test it at run-time like this:
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, let's suppose I want to implement a portable arithmetic right shift; if I had to check this every time a function is called, this would be a huge performance impact, so I would like to do it at compile time, if possible.
If there exist no portable way of doing this check, is there a way to do this by checking on the best-effort basis, like checking with ifdefs for a specific compiler/platform?