Branching elimination using bitwise operators
I have some critical branching code inside a loop that's run about 2^26 times. Branch prediction is not optimal because m is random. How would I remove the branching, possibly using bitwise operators? bool m; unsigned int a; const unsigned int k = ...; // k >= 7 if(a == 0) a = (m ? (a+1) : (k)); else if(a == k) a = (m ? 0 : (a-1)); else a = (m ? (a+1) : (a-1)); And here is the relevant assembly generated by gcc -O3 : .cfi_startproc movl 4(%esp), %edx movb 8(%esp), %cl movl (%edx), %eax testl %eax, %eax jne L15 cmpb $1, %cl sbbl %eax, %eax andl $638, %eax incl %eax movl %eax, (%edx) ret L15: