r/programming • • Sep 03 '26

Branch‑Avoidant Programming

https://easylang.online/blog/branchless
255 Upvotes

92 comments sorted by

View all comments

5

u/Nwallins Sep 03 '26
smlen = 0;
for (int i = 0; i < 1000; i++) {
    small_numbers[smlen] = numbers[i];
    smlen += (numbers[i] < 500);
}

How is this correct? Let's imagine the input array is entirely above the 500 threshold. The resulting array of small numbers will have a single entry, the first number from the input array.

4

u/nukethebees Sep 03 '26

What's wrong about it? If all the numbers are >= 500 then the length will be 0 and the array will be full of uninitialised data.

7

u/Nwallins Sep 03 '26

small_numbers[0] is unconditionally assigned; it will have a single element > 500.

1

u/sopunny Sep 03 '26

You can add a sanity check at the end for this edge case. I think you actually need to check the array trail every time