Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rewrite this if-else statement so that it doesn't use a jump?

Tags:

c

if-statement

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.

like image 475
gruszczy Avatar asked Dec 22 '22 15:12

gruszczy


1 Answers

y = a ^ ((x - 1U) & (a ^ b));

This uses bitwise x-or

like image 166
6502 Avatar answered Jan 26 '23 00:01

6502