c / expert
Snippet
Branchless Conditional Logic for CPU Pipeline Optimization
Branch mispredictions in performance-critical loops trigger severe CPU pipeline flushes. By leveraging arithmetic bit-shifts to construct sign masks, conditional selections like maximum or absolute value computation can be performed entirely without branching instructions (if/else), achieving predictable throughput on modern out-of-order processors.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>#include <stdint.h>int32_t branchless_max(int32_t a, int32_t b) {int32_t diff = a - b;int32_t mask = diff >> 31;return a - (diff & mask);}int32_t branchless_abs(int32_t x) {int32_t mask = x >> 31;return (x + mask) ^ mask;}int main(void) {printf("Max(-5, 10) = %d\n", branchless_max(-5, 10));printf("Abs(-42) = %d\n", branchless_abs(-42));return 0;}
Breakdown
1
int32_t mask = diff >> 31;
Generates a bitmask of all 1s (0xFFFFFFFF) if diff is negative, or all 0s if non-negative, using arithmetic right shift.
2
return a - (diff & mask);
Uses bitwise AND with the mask to conditionally subtract the difference without any branching hardware instructions.
3
int32_t mask = x >> 31;
Extracts the sign bit extended across all 32 bits (-1 for negative numbers, 0 for positive).
4
return (x + mask) ^ mask;
Computes Two's Complement negation branchlessly via two's complement identity ~(x - 1).