Reason behind declaring iteration variables on a method level Lately, I have been in touch with some C++ snippets, and I have a very strange observation on the tiny detail:
Most of the times, I see, that people declare iteration variables outside of the for/while definitions, and then initialise them inside for/while definitions, like:
int i, j, k;

for(i = 0; ..; ..) { } //note, this omits declaration of &quot;i&quot;

I wonder what is the reason behind this? why would one want to scope a loop-level temporary variable and its identifier on a method-level?
Is this conventional? does it help compilation's lexical translation? an optimisation for static code analysis? what is the purpose?
It (important) certainly looks ugly, especially when there are numerous variables in the method; it (important) reserves variable identifiers (on a method-level); and (less important) it definitely occupies more space in the memory.
Any points?
Appreciations.
No, this is not conventional if writing C++. People who do this might have a C background. Indeed, in old C89, you had to declare all variables at the beginning of your scope. Of course, even if you didn't start programming with C89, you might have been exposed to out-dated guides or material and you might have picked up the habit. As we know, it is sometimes difficult to unlearn something.
In general, variables should be declared as close as possible to their actual site of usage and thus we don't unnecessarily pollute the scope, exactly as you point out. This is also defensive programming, it helps readability and protects from mistakes.