Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of a 'while' and 'for' loop?

Tags:

c++

c

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?

like image 520
T.T.T. Avatar asked Oct 24 '11 19:10

T.T.T.


People also ask

What is the scope of a for loop in Python?

In Python, for-loops use the scope they exist in and leave their defined loop-variable behind in the surrounding scope. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.

What is the difference between a While and for loop?

The major difference between for loop and while loop is that for loop is used when the number of iterations is known whereas, in the while loop, execution is done until the statement in the program is proved wrong.

Which is better While or for loop?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

What is the scope of a variable declared inside a loop?

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. What ever the variables declared inside the block ,the scope restricted to that block. So J scope is restricted to inside that block. That is for loop.


2 Answers

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 before i is incremented.

while(int a = foo()) {     int b = a+1; }  for(int i=0;     i<10;     // conditional expression has access to i     ++i)      // final expression has access to i {     int j = 2*i; } 

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.

like image 148
bames53 Avatar answered Sep 22 '22 15:09

bames53


Anything declared in the loop is scoped to that loop and cannot be accessed outside the curly braces. In fact, you don't even need a loop to create a new scope. You can do something like:

{
   int x = 1;
}

//x cannot be accessed here.
like image 24
Mike Christensen Avatar answered Sep 23 '22 15:09

Mike Christensen