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


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

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


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


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