by lifthrasiir · 7y ago · 0 comments
Here, trying to access out[index-1] would error.
Yes, you could then guard against that of course, but then that's even more code to maintain.
If this code is a critical hot-path then sure, micro-optimizations can make sense but doing so without over-commenting and a rigorous test suite to catch introduced bugs is a recipe for disaster.
while (howmany != 0) {
val = random();
if( val is odd) {
out[index] = val;
index += 1;
}
howmany--;
}
vs while (howmany != 0) {
val = random();
out[index] = val;
index += (val bitand 1);
howmany--;
}
Both of these store a list of odd numbers in out[], with "index" containing the resulting count of how many numbers are in out[]. Both will have an "index" (count) value of 0 if all inputs were even, and neither attempts to access out[index-1].