(a)
if(foo & 1) bar = a;
else bar = b;
(b)
bar = (foo & 1) ? a : b;
(c)
bar = b + (a - b)*(foo & 1);
(d)
/* -(foo & 1) is either all zeros or all ones */
bar = b + ((a - b) & -(foo & 1));
Example 4: (a) Conditional that requires two branch instructions; (b) a less-obvious conditional; (c) using arithmetic to avoid branches; (d) using logical operations to avoid branches.
Back to Article