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 "i"

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?


  • $\begingroup$ This question is more suited for stackoverflow.com. These declarations were required in C. So either 1) You are looking at C snippets, not C++, 2) The code was migrated from C (C is a subset of C++), or 3) The code was written by a person who knew C but didn't know C++ (or simply didn't know C++). Overall, it's definitely a bad practice (since the variable scope is larger than required). $\endgroup$
    – user114966
    Commented Mar 8, 2021 at 7:04
  • $\begingroup$ I'm not sure, that this question fits StackOverflow better. On-topics say, that I can ask here about programming language semantics; regarding other points, I have seen this in a number of different snippets.. which, of course, doesn't mean it's correct. :) hence, my question. By the way, could you elaborate on C case? why this was required in C? $\endgroup$ Commented Mar 8, 2021 at 7:11

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.