What is the difference when defining an iterative variable? Does memory allocate?

int i; for (i = 0; i < someVal; i++) { } 

and

 for (int i = 0; i < someVal; i++) { } 
  • one
    In c ++, a section of memory can be used by other local variables that are declared in other {} if there are any (2-4 bytes, version and manufacturer s / s ++ affects). In c # there will be no difference. - nick_n_a

2 answers 2

This will only affect the scope of the variable i . In the first case, you can refer to a variable outside the loop, for example:

 int i; for (i = 0; i < someVal; i++) { }; i = 2 + 2; 

In the second case, the scope of i limited to the body of the loop.

  • The break option is probably more useful, to find out at which iteration the loop ended - VladD 4:56 pm
  • but what about question 2? - nick_n_a pm
  • @nick_n_a: And does not affect memory, most likely the counter will generally be pushed into the register. - VladD 5:02 pm
  • one
    @nick_n_a, and if the programmer is an idiot? - PinkTux
  • 2
    naturally. Compilers are pretty smart right now. My favorite is “don't try to cheat the compiler” :) - KoVadim

In addition to the perfectly correct answer @Flownee: how and where exactly the variables are declared is not important. It is only important where in the code this variable is still needed.

Modern compilers on popular platforms perform aggressive optimization, and use the variable memory for other variables not at the end of its scope, but really as soon as it is no longer needed in the code. In the absence of using the variable after the cycle, both options are equivalent, and in theory they will give the same memory allocation.