Reputation: 8616
#define CONVERT(val, qin, qout) ((qin > qout) ? (val >> (qin-qout) ) : (val << (qout-qin)))
void f(void)
{
...
y = CONVERT(x, 25, 31);
}
Is the above macro going to be evaluated by GCC at compile time? I mean the (qin > qout)
part. I am trying to have only y = x << (31-25)
after the compilation is done.
Upvotes: 0
Views: 336
Reputation: 213711
The qin > qout
part will end up as an integer constant expression in this case, which the compiler can optimize into 1
or 0
in theory.
In practice, it doesn't even do that. Looking at how real compilers actually treats your example, gcc and clang at -O0
(optimizations off) only generates the code for the left shift, omitting the conditional check and branch of ?:
, as well as the second operand which is never true.
The machine code ends up boiling down to the equivalent of y = x << 6;
, completely branch free.
Upvotes: 4