c# – What is the difference between the two options?

Question:

What is the difference when the iteration variable is defined differently? Does it affect memory allocation?

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

and

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

Answer:

This will only affect the scope of the i variable. In the first case, you can refer to the 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 cycle.

Scroll to Top