# Should “counters” used in Do, Table, … within Module be declared as local?

I have little to no understanding of how Mathematica handles scoping, so the question may seem a little bit funny.

What is the preferred way:

Test[] = Module[{},
Do[Print["Hello ", i], {i, 5, 50, 5}];
];
Test[];


Or:

Test[] = Module[{i},
Do[Print["Hello ", i], {i, 5, 50, 5}];
];
Test[];

• First option is all you need. Mathematica handles scoping a couple of different ways. Table/Do/etc. create their own scope for an iterator, and I believe they use textual scoping just like With (but unlike Block and Module). This may help: reference.wolfram.com/language/guide/ScopingConstructs.html. In particular look at "Learning Resources". – mfvonh Dec 2 '14 at 20:41
• One way to test such things is to use, and show, an explicit setting for your symbol. Try for example this small variation on your code: Module[{i=-20}, Do[Print["Hello ", i], {i, 5, 50, 5}]; i]. Notice that the i at the end is the Module variable and is not related to the i of the loop. – Daniel Lichtblau Dec 2 '14 at 20:48
• @mfvonh Actually Table & related functions use the same type of scoping as Block (not like With). Try Table[i = 1; Print[i], {i, 5}]. – Szabolcs Dec 2 '14 at 21:00
• Also check the thirds heading here – Szabolcs Dec 2 '14 at 21:02
• for entertainment ask a "c" programmer what this does.. i = {4, 5}; Do[Do[ Print[ i ] , {i, i}], {i, i}] – george2079 Dec 2 '14 at 21:05

One type of scoping uses "textual" replacement, meaning the symbolic layer of evaluation is bypassed. For example:

With[{i = 1}, SymbolName[Unevaluated[i]]]


SymbolName[Unevaluated[1]]


This property of With makes it very handy sometimes, simply as a way to avoid evaluation where it is not wanted. I learned this myself in this question.

Compare that to:

Block[{i = 1}, SymbolName[Unevaluated[i]]]


i

Module[{i = 1}, SymbolName[Unevaluated[i]]]


i\$24225

And turns out my comment above was inaccurate. Table does not use textual scoping:

Table[SymbolName[Unevaluated[i]], {i, 1, 1}]


{i}