Glancing over the other (very good) answers, there's a point I didn't see getting made. (If it did get made I missed it and apologize.)
I'm going to give you two snippets of seemingly semantically identical code.
Snippet #1:
for (int a = 0; a < arr.length; a++) {
/* do some work here */
}
Snippet #2:
int b = 0;
while (b < arr.length) {
// do work
b++;
}
They look like they do the same thing, right? Now let me add one single line to each snippet and let's see what happens:
Snippet #3:
for (int c = 0; c < arr.length; c++) {
/* do some work here */
}
printf("%d\n", c);
Snippet #4:
int d = 0;
while (d < arr.length) {
// do work
d++;
}
printf("%d\n", d);
So when I compile a junk file with those four snippets embedded (plus some glue to have arr.length mean something) I get the following error:
$ clang junk.c
junk.c:20:17: error: use of undeclared identifier 'c'
printf("%d\n", c);
^
1 diagnostic generated.
Using the for
loop, it turns out, allows you to provide more locality to your dummy counter variables, etc. This gives you greater leeway in reusing variable names without chance of collision (albeit at the expense of increasing potential shadowing).