cpp / expert
Snippet
Mask-Based Selection for Branch-Free Evaluation
Branching (if/else) can cause pipeline stalls due to mispredictions. Expert C++ code often uses bitwise masks to perform selections. When the condition is 1, the mask becomes 0xFFFFFFFF (all bits set), selecting the true value. When 0, the mask is 0x00000000, selecting the false value via the bitwise OR.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
int safe_select(int condition, int true_val, int false_val) {// condition must be 0 or 1int mask = -condition;return (true_val & mask) | (false_val & ~mask);}// Usage for performance-critical clampsint fast_clamp(int val, int min, int max) {val = safe_select(val < min, min, val);val = safe_select(val > max, max, val);return val;}
Breakdown
1
int mask = -condition;
Exploits two's complement: -1 is all 1s, -0 is all 0s.
2
(true_val & mask) | (false_val & ~mask)
Combines the masked values into a single result without a jump instruction.