by XJ6 · 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].> count of how many numbers are in out[]
is not true, in the latter case it's a count of how many numbers you want to be in out[].
Consider what happens if howmany is 1 and it generates a single even number. In the original you have an empty array and index 0, in the newer one you have an array e.g. [2] and an index 0.
Yes, you can solve this by 'manually' only returning the first "index" elements but it's just asking for trouble and a source of bugs as seen in your attempt to describe it have a difference between the reality and your description.
You might not consider that to matter, but the point I'm trying to make isn't just nitpicking, it's that there are certain expected behaviours from code, and an array which is "all odd numbers, except maybe all odd but one last even number" is bound to lead to broken expectations.