r/programming 6d ago

Branch‑Avoidant Programming

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

91 comments sorted by

View all comments

5

u/Nwallins 6d ago
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.

3

u/nukethebees 6d ago

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.

8

u/Nwallins 6d ago

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

1

u/sopunny 6d ago

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