+ 1

Is it a good practice to declare the counter inside a loop or outside?

for ( int i = 0; i > 5; i++ ) {} or int i for ( i = 0; i > 5; i++ ) {}

5th Dec 2016, 6:19 AM
Alabi Oyewumi Emmanuel
Alabi Oyewumi Emmanuel - avatar
5 Answers
+ 8
As for where to declare a counter? its better outside the loop...as you have rightly pointed out, later on it could be a resource for bugs. More so the counter outside mostly makes cleaner codes. I.e easier to locate and read code.
8th Dec 2016, 7:07 AM
CMD
CMD - avatar
+ 3
It's better inside, because after the for loop, you will not use the i, and its local to the for iteration. after the for ends, you will free that memory, since i is no longer used. Also, if you have multiple for loops in larger projects, you will forget about if you already declared the int i, or you will have to just asign it.
5th Dec 2016, 6:38 AM
Nahuel
Nahuel - avatar
+ 3
In the example with the for loop, Declaring i in the for loop guarantees that its value is not accessible after the loop terminates. If you declare i before the loop, on the other hand, it is possible that at some later point the same variable i is re-used, and now you have to worry about whether there was a preceding assignment or whether it retains its old value of 5. This could very well be a source of bugs.
5th Dec 2016, 6:45 AM
Alabi Oyewumi Emmanuel
Alabi Oyewumi Emmanuel - avatar
0
You've tagged this question with "for". In some languages, like JS, python, variable need not be declared before use. So no declaration in necessary outside the loop. In other languages like C, Java, variable has to be declared. In any case, it is not a matter of convention here, but syntax.
5th Dec 2016, 6:39 AM
Rishi Anand
Rishi Anand - avatar
- 1
it's better to declare inside the for loop
5th Dec 2016, 6:39 AM
Madison Lintz
Madison Lintz - avatar