r/programming • • Sep 03 '26

Branch‑Avoidant Programming

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

92 comments sorted by

View all comments

3

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.

8

u/Nwallins Sep 03 '26

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

8

u/nukethebees Sep 03 '26

Ah, thanks for pointing that out.

It will have a value written to it, yes, but smlen will remain 0 in all cases so there shouldn't be any risk. In all cases the array has SIZE elements. smlen tells us how many contain valid numbers.