Increment or decrement to target without branching

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Andrew Davie

Here's a really cool bit of code. The task is to increment or decrement a current value by one until it hits a target value. Usually you'd do this with a couple of if statement. It can be done without branches like this...

current += (current < target) - (current > target);

I'll leave it to the reader to figure out how it works (hint: in C a conditional has an exact numerical value of 1 or 0).

Andrew Davie

I forgot to mention - if the current and target are the same, this code still works.

current < target:   current += (1) - (0)  (ie: increments current)
current == target:  current += (0) - (0)  (ie: no change)
current > target:   current += (0) - (1)  (ie: decrements current)