I am wondering if it is good practice to increment a factorial within the increment statement of a for
loop rather than the body of the for
loop?
Below shows the factorial being incremented multiplicatively within the increment statement:
for(Count = 1; Count <= 10; Factorial *= Count, Count++);
An alternative is incrementing the factorial within the body of the for
loop:
for(Count = 1; Count <= 10; Count++)
{
Factorial *= Count;
}
As the third parameter in a for
loop is used for increments, is it a good or bad practice/code style to increment in this way? I believe it doesn't have any trade-off for readability + neatens up the code by saving some space, and although it doesn't change the outcome of the program, are there any negatives to using for loops in this way?
Do not move loop body into loop header.
The separation of loop components into loop body and loop header greatly improves readability.
Your readers will be able to tell loop's "payload" (i.e. Factorial *= Count
) from loop's control (everything else) with a quick glance at your second code snippet. Your first code snippet would have your readers scratch their head for a few seconds before they realize that (1) there is a semicolon at the end of the for
loop, and (2) the payload of the loop is in the header.
The fact that the compiler would probably generate the same code in both cases should not be a factor at all.