Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable declaration

 
ravinderSingh singh
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • 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
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • 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
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic