Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use the same variable name in loops?

I just started programming in C++, and while coding I started noticing that I had a lot of for loops in my code, then I started thinking.

In for loops, when you create variables like: for (int **i**=1;i<10;i++), what happens to the i after the loop is done?
Is it okay to create multiple for loops with the same variable name?
What about creating variables inside while loops?

like image 228
Salthy Avatar asked Dec 18 '22 03:12

Salthy


1 Answers

... what happens to the i after the loop is done?

It goes out of scope.

Is it okay to create multiple for loops with the same variable name?

Yes, it's OK and widespread practice to do so.

What about creating variables inside while loops?

Variables created inside of while loops are local to the while loops body. They are different from running variables created in the first part of the for loop header, which is executed only before the loop is entered first time.

like image 114
user0042 Avatar answered Dec 24 '22 01:12

user0042