Error "GNU C Programming Tutorial"
I was reading the GNU C Programming Tutorial and I think I caught a very small and subtle error. On this chapter . In a function in a loop : delete_multiples_of_prime(...)
for
delete_multiples_of_prime (int prime)
{
int index, multiplier = 2;
for (index = prime * multiplier; index < ARRAY_SIZE; index = prime * multiplier++)
sieve[index] = DELETED;
}
I think the problem is with the incremental part for
. The author used the post-increment operator instead of the pre-incremental operator, meaning that I think the loop will run with the initial index value twice.
I'm right?
Note: I'm pretty sure I'm right and I wouldn't have posted it if I found it somewhere else but was there ... That makes me doubt it. Of course, I know that even if I'm right, the performance difference is negligible.
source to share
You are correct that the loop runs twice for the first index.
However, this is not a bug, because assignment is an idempotent operation, so multiple assignments for a given index will have no additional effects or side effects. The function will always work the same, even if the first index is repeated twice.
In terms of performance, the difference should be negligible, as there will only be one additional assignment per function call. (Due to idempotency, it can also just be optimized by the compiler).
That being said, for clarity, and in case the body of the loop for
has ever been changed to no longer be indempotent (for example by adding a statement printf
), I personally would use prefix increment:
for (index = prime * multiplier; index < ARRAY_SIZE; index = prime * ++multiplier)
source to share