What is the scope of a while and for loop?
For example, if I declared an object within the loop, what is its behavior and why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In the following examples all the variables are destroyed and recreated for each iteration of the loop except
i, which persists between loop iterations and is available to the conditional and final expressions in the for loop. None of the variables are available outside the loops. Destruction of the variables inside the for loop body occurs beforeiis incremented.As for why; loops actually take a single statement for their body, it just happens that there’s a statement called a compound statement created by curly braces. The scope of variables created in any compound statement is limited to the compound statement itself. So this really isn’t a special rule for loops.
Loops and selection statements do have their own rules for the variables created as a part of the loop or selection statement itself. These are just designed according to whatever the designer felt was most useful.