Reputation: 1
Please tell me what's the difference of these two snippets of code:
int i = 0;
for(i; i < test; i++) {...}
and
for(int i = 0; i < test; i++) {...}
Is there any difference between these ways of initializing the i
-increment variable? Does it affect anything or not?
Upvotes: 0
Views: 2176
Reputation: 10055
In both cases, the variable is being defined once (no significant performance or memory issues). The differences come in scope and representation. On the first case i
will be available outside the scope of the for
statement.
The first case is useful, for example, if you want to find a the particular index of an element (tough there do exist better alternatives to this approach) or if you want to iterate until a certain condition is met and, then, know which index did your loop stop at.
Upvotes: 1
Reputation: 6572
in case one you can use i variable in out side of the for loop scope. in case two you cant do so. Only can use in for loop scope.
Upvotes: 1
Reputation: 121427
Difference is the scope of the variable i
.
In the first one, i
is visible outside the for loop and in the second one, it isn't.
Upvotes: 5
Reputation: 360026
The second one is idiomatic. The first one is not, and as such violates the principle of least astonishment.
Only use the second one if you need access to i
before or after the for
loop. I see nothing in this code to suggest that is the case, however.
Upvotes: 0