Is there any difference if I were to write something like this:
int row,col;
for(row = 0; row < data.length; row++){
for(col = 0; col < data[row].length;col++){
//do something
}//end for loop(columns)
}//end for loop(rows)
for(row = 0; row < data.length; row++){
for(col = 0; col < data[row].length;col++){
//do something
}//end for loop(columns)
}//end for loop(rows)
compared to:
for(int row = 0; row < data.length; row++){
for(int col = 0; col < data[row].length;col++){
//do something
}//end for loop(columns)
}//end for loop(rows)
for(int row = 0; row < data.length; row++){
for(int col = 0; col < data[row].length;col++){
//do something
}//end for loop(columns)
}//end for loop(rows)
Are there any bennefits from either one?
5
Quick answer: most of the time I don’t care about the value outside the loop, so I use the second form.
Occasionally I’ll want the “first index” where I’ll put a break (or an exit condition on the loop) so that the value represents as far as I got. Then I’ll use the first form, but with a break or a loop condition that causes it to stop early.
…e.g. find the index of the first non-zero value in an array.
EDIT: I just looked more closely at your code… I would NEVER reuse the same index variable just for the sake of preserving variable declarations 😉 lol!
Both versions may have a specific purpose.
1 Variables inside
Used for iterating(yes, I know about iterators and enhanced loop, but let’s use the old for)
2 Variables outside
Let’s say we want to find the index of an item from some array and we want that index to use for something else. You can’t use the variables for the loop scope because you will need the index so your index must be outside the loop scope.
Example:
int i;
for (i = 0; i < length; i++) {
if (someConditionAppliedForAnElement(arr[i])) {
break;
}
}
if (i != length) { /* logic here */ }
Of course, this is just an example, there are better ways to do this task, but I just wanted to point that sometimes, loop scope doesn’t fit.
By the way, for your sample I’d use loop scope indexes.