In general for any language, if you reuse variable names, and then you decide to refactor part of your code into another method, you end up having to add or edit declarations.
int i;
for(i = 0; i < 10; ++i) {
printf("%d\t%d\n", i , i * i);
}
for(i = 0; i < 10; ++i) {
printf("%d\t%d\n", i , i * i * i);
}
Suppose you take the second loop and move it to a print_cubes
method. You will not be able to just cut and paste the for loop, as i
will have no declaration there. A good IDE might be able to insert the declaration, but it might worry about the side-effects on i
in the code you've typed.
In general, compilers can consolidate used variables by what are called graph-coloring algorithms. Consider this variant:
for(int i = 0; i < 10; ++i) { // BLOCK 1
printf("%d\t%d\n", i , i * i);
} // END BLOCK 1
for(int j = 0; j < 10; ++j) { // BLOCK 2
printf("%d\t%d\n", j , j * j * j);
} // END BLOCK 2
The compiler lists the used variables: i
, j
. It lists the blocks being used: BLOCK 1, BLOCK 2. The parent function is also a block, but i
and j
are visible only in BLOCK 1 and BLOCK 2. So, it makes a graph of the variables, and connects them only if they are visible in the same block. It then tries to compute the minimum number of colors needed to color each vertex without giving two adjacent vertices the same color, similar to the Haken-Appel Four Color Theorem. Here; only one color is needed.