• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Variable declaration

 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you declare a variable in a for or while loop, is a new variable created each time through the loop?

For example,

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

Does this mean the variable var will be declared 10 times during execution of the loop?

Thanks
 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes it will be created 10 x but it will also go out of scope 10 x.

loop execution starts
variable created
1st iteration of loop ends and variable goes out of scope (it's gone)
2nd iteration of loop starts
variable created
2nd iteration of loop ends and variable goes out of scope (it's gone)
and so on so forth
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Does this mean the variable var will be declared 10 times during execution of the loop?



The variable is declared once. Declaring something is a compile-time directive, not an executable statement. Any initializer in the declaration ( var = 3 ) is an executable statement.

A variable declared inside a block { ... } is allocated memory on a push-down/pop-up stack every time the block is entered. The memory is given back every time the stack is exited. Statements in the block starting at the point of declaration can access the variable.

In a for while or do statement, the block is entered and exited with every repetition of the loop.
[ November 19, 2004: Message edited by: Mike Gershman ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic