Reputation: 5166
I have a very basic question about scoping rules. When you declare a variable within a loop, say:
while ( /*some condition*/ )
{
int a = 0;
//Remaining operations
}
Is a new int
variable declared in every iteration of the loop? Or is it that a
is destroyed at the end of every iteration and freshly created again? How does the compiler in Java or C++ understand and implement this?
Upvotes: 4
Views: 260
Reputation: 29164
You have to differentiate between the logical level and the implementation level.
From a logical point of view, the variable is not really 'created' or 'destroyed', but that's how you could probably imagine it. The variable is simply declared within some scope, so it's guaranteed to exist (you can assign to it and read its value), it's initialized at the beginning of the block (so it has the value 0
) and it isn't visible outside the code block. Thats what the language definition says. In C++, if you omit the initialization (i.e. the =0
part), the language doesn't make any assumption about what the value is (so the compiler is free to "reuse" the memory location). In Java, afair, the initialization is implicit, so a
will also be set to zero, if you omit the initialization.
At implementation level, the compiler is more or less free to do whatever it wants, as long as it fulfills the above specifications. So in practise, it will most likely reserve some space on the stack and use this same memory for every iteration to store the value of a
. Since you've used an initializer, the value 0
will be written to this location at the beginning of every loop. Note, that if a
isn't used within the scope, the compiler is also free to simply optimize it away. Or, if possible, it can assign it to a CPU register.
However, theoretically, a compiler could also reserve a "new" memory location for a
in every iteration and clear all of them at the end of the loop (although this could result in StackOverflow (!) for long loops...). Or use garbage-collected dynamic memory allocation (which would result in poor performance...).
Upvotes: 3
Reputation: 1089
Basically, a is a local variable, which is initialized every iteration in the loop with the value 0, and then destroyed, and so on, until the loop is finished when it is ultimately destroyed
Note:
while(//Some Condition)
would comment out the right parenthesis, and therefore the code would not run anyway
Correct this to:
while(/* some condition */)
Upvotes: 2
Reputation: 500357
I find it easier to think about a
as being the same variable that gets repeatedly created and destroyed.
Upvotes: 2
Reputation: 35557
a
create and destroyed after each and every iteration.
Upvotes: 1
Reputation: 136012
It's declared only in source code. In bytecode it simply uses a local variable on the stack which will be initialized with 0 at every iteration. The difference with declaration outside the loop is that when it is inside loop JVM will reuse the variable which a
occupied.
Upvotes: 1