This example is a simple case related to my question.
Case 1: declaring out of the loop
List<List<int>> matrix = [[1,2,3],[4,5,6],[7,8,9]];
List<int> o;
for(int i=0; i<matrix.length; i++) {
o = List.from(matrix[i]);
for(int e in o)
print(e);
}
Case 2: declaring inside the loop
List<List<int>> matrix = [[1,2,3],[4,5,6],[7,8,9]];
for(int i=0; i<matrix.length; i++) {
List<int> o = List.from(matrix[i]);
for(int e in o)
print(e);
}
Does it matter where I declare the variable? Why?
The scope of a local variable should be as small as possible. Thus, declaring a variable inside the loop is a better practice.
The advantages of doing so:
i
and the same variable is referenced in multiple loops, it may get confusing as to what value the variable holds at any part of the program.Declaring variable inside the loop is good only if you do not need to reuse the updated variable value like:
int counter = 0;
for(final i in range(1, 10)) {
counter++;
// use variable counter here as a "counter"
}
In the snippet below, using the variable counter
as a counter is invalid as the variable is reinitialized at the start of each loop
for(final i in range(1, 10)) {
int counter = 0;
counter++;
// use counter here as a "counter"
}
If you do want to use a variable as a counter(or any other purpose) and update its value inside a loop and use it outside of the scope of the loop then only declare the variable outside of the loop.
Refrences: