• Post Reply Bookmark Topic Watch Topic
  • New Topic

while loop variable???  RSS feed

 
Robert Johnson
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i declare a variable in a while loop can i use that variable outside the while loop?
 
Harish Kashyap
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the scope of that variable is within the while loop

as soon as the program exits the while loop the variale is lost.

if you have a variable declared with the same name outside the while loop, that will be accessed outside the loop.

int i=5;
while(...)
{
int i=2;
// i=2 within the loop
}
// here i=5
 
Jussi Taimiaho
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you have a variable declared with the same name outside the while loop, that will be accessed outside the loop.


More correct way to say this would be, that if you declare a variable outside the loop, the variable's scope includes the loop. If you declare the variable inside the loop, the variable is accessible only within the loop.
 
s choukse
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you define a variable in any block of code then that variable is avilable inside that block and within all the blocks contained in that block.
For example:
Class
{
method
{
int i;
i is accessable here
for loop
{
i is accessable here
}
}
i NOT is accessable here
}
Hope this explains.

s choukse
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!