+ 2

Declaring variable in for loop

if i declare a variable inside for loop. is a new variable created in each iteration? for(int a=0; a<x;a++){ int y=3; y++; } Edited i am asking about java.

1st Jan 2018, 5:03 AM
sal sal
sal sal - avatar
3 Antworten
+ 14
Yes. If you don't want this, you may nest the declaration of y into the initialization section of the for loop (some languages may not allow this), or simply outside the loop. for (int a = 0, y = 3; a < x; a++, y++);
1st Jan 2018, 5:07 AM
Hatsy Rei
Hatsy Rei - avatar
+ 11
Declare it prior to the loop. int y = 3; for (int a=0; a<x; a++) y++;
1st Jan 2018, 5:18 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
but if i want to use y outside for loop. what is the solution?
1st Jan 2018, 5:16 AM
sal sal
sal sal - avatar