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++) { }
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++) { }
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.
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.
Source: https://ru.stackoverflow.com/questions/547528/
All Articles