Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable Declaration ..

Status
Not open for further replies.

fravio

Programmer
Nov 9, 2001
10
0
0
IN
Hi,

If we are declaring a variable inside a loop, what will happen to the instance of that variable before the next iteration? Does it mean that each time the variable is created though its not being explicitly destroyed at the end of each iteration...Case is same for local function variables also..This may sound funny...but i just want to know how it is...

Fravio..
 
Code:
for (i=0; i<10; ++i)
{
   // i's scope exists until the loop ends
   int x = 0; // x's scope exists until the loop ends

   // however, x is intialized every iteration of loop
}
// can't see i or x
James P. Cottingham

I am the Unknown lead by the Unknowing.
I have done so much with so little
for so long that they think I am now
qualified to do anything with nothing.
 
In the loop above, x will be re-initialized to zero every time.

Matt
 
in the for loop above:

for (i=0; i<10; ++i) I assume that i is declared above the for loop, so i will still be in scope after the loop ends

Ricky



Failure is not falling down, it's staying down.
 
You would like to assume that and by design that is how it is SUPPOSED to be. However,


for(int i = 0;i<7;i++)
{
}

for(int i = 0;i<10;i++)
{
}

Will produce multiple definition errors. If you instead do

{
for(int i = 0;i<7;i++)
{
}
}

{
for(int i = 0;i<10;i++)
{
}
}


there will be no issues

Matt
 
Thanx guys..its become more clear now..
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top