Ben
Ben

Reputation: 1349

Re-writing code to remove conditional statements

Is it possible to re-write the following so that it doesn't contain any conditional statements? I'm thinking there might be some clever trick using something like bitwise operations?

int a = // some value
int b = // some other value between 0 and max int
if(b >= 3)
{
    return a + 1;
}
else
{
    return a;
}

EDIT: to be clear, I'm not looking for a generic way of removing conditionals. I'm looking for a trick to remove the conditionals from this very specific code. Think of it as an academic puzzle.

To give an example, one way to remove conditionals (which happens to yield perf gains in some situations) is to precompute a lookup table and index into that with b instead. In this particular case this is tricky because b could be a very large number. Is there another way?

Upvotes: 0

Views: 894

Answers (4)

Ivan Stoev
Ivan Stoev

Reputation: 205629

Here you go

return a - ((2 - b) >> 31);

Explanation:

r = 2 - b, < 0 (i.e. high bit set) for b >= 3

r >> 31, = -1 for b >= 3, 0 otherwise

Upvotes: 4

Dave S
Dave S

Reputation: 3468

uint a = // some value
uint b = // some other value between 0 and max int
bool c = b & 0xFFFC
return a + Convert.ToInt32(c);

The fastest will probably be as bitwise operations tend to be very fast

uint a = // some value
uint b = // some other value between 0 and max int
return (b & 0xFFFC) ? a+1 : a;

Upvotes: 2

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

?: operator. (but yet it contains conditional statement.)

return b >= 3 ? a + 1 : a;

or

return a + (b >= 3 ? 1 : 0);

Is it possible to re-write the following so that it doesn't contain any conditional statements?

It is not possible to make it work out of no where. you must check this condition any way. There is no magic.

If you want to make your program faster by removing this condition then you picked wrong way. this is micro optimization.

Upvotes: 0

Roka
Roka

Reputation: 516

You could make it better by doing this:

int a = // some value
int b = // some other value between 0 and max int
return (b >= 3) ? (a+1) : a;

Upvotes: 0

Related Questions