A branchless alternative implements conditional behavior without allowing the input condition to select different control-flow paths. Instead of an if branch, it uses a conditional move such as CMOV, so the same instruction sequence executes whether the predicate is true or false. This avoids branch prediction based on secret-dependent conditions and can support constant-time implementations. section 10.5
Use the technique with these engineering rules:
- Replace a conditional update with a predicate-controlled move rather than relying on an input-dependent branch. section 10.5
- Check timing behavior with both irregular and predictable inputs; ordinary branches may run differently when branch prediction succeeds. section 10.5
- Treat compiler and processor details as part of the implementation: the example uses GCC inline assembly and Intel CMOV instructions. section 10.5
Summing values above a threshold
A conventional loop adds array[i] only when array[i] exceeds 500. The branchless version initializes increment to zero, conditionally moves array[i] into increment with CMOVG, and then always adds increment. Both versions return the same sum, while the benchmark reports different timings for random and sorted arrays.
