HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Is it bad practice to increment more than one variable in a for loop declaration?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
incrementdeclarationpracticethanmorebadlooponeforvariable

Problem

While coding today, I came across the following loop in C#:

for(int x = 0; x < max_x_index; x++){
    for(int y = 0; y < max_y_index; y++, count++){
        some2DarrayRepresentedBy1D[count] = ...;
    }
}


Would this be consider bad practice? Would the following be a better way to achieve the same result:

for(int x = 0; x < max_x_index; x++){
    for(int y = 0; y < max_y_index; y++){
        some2DarrayRepresentedBy1D[count] = ...;
        count++;
    }
}


Would you allow both through, for example, a code review or would you tag the first example for being obscure?

Solution

I would agree with the OP in that the second code block would be the best approach.

Reason - readability. In my opinion, the variable incremented in the for loop statement should only be used for keeping count of how many times we're looping. count might be set before the loop, it might also be incremented / decremented in several different loops. But in either case, count isn't used to keep track of the progress of the current loop - y is in this case.

So, I would say that it's best practice, for readability sake, to only increment the variable used to loop through the for loop in the for loop line itself.

Context

StackExchange Code Review Q#36904, answer score: 28

Revisions (0)

No revisions yet.