I am not trying to optimize anything, so please don't tell me, that premature optimization is root of all evil. I am trying to solve a problem and I can't find the third solution.
The problem goes like this:
if (x)
y = a;
else
y = b;
x
can only be 0 or 1. How to write this condition without a jump?
One solution, with a data structure, is:
int temp[2] = {b, a};
y = temp[x];
Another arithmetic solution is:
y = x * a + (1 - x) * b;
There is supposed to be a third one, a logical solution. Do you know how it looks like? Please give a solution in C.
y = a ^ ((x - 1U) & (a ^ b));
This uses bitwise x-or
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With