This week's book giveaway is in the Security forum.
We're giving away four copies of Securing DevOps and have Julien Vehent on-line!
See this thread for details.
Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

while loop variable???  RSS feed

 
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?
 
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
 
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.
 
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!