Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration of variables within a loop

Tags:

java

c++

loops

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?

like image 455
SoulRayder Avatar asked Jan 11 '23 11:01

SoulRayder


2 Answers

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...).

like image 198
MartinStettner Avatar answered Jan 18 '23 11:01

MartinStettner


I find it easier to think about a as being the same variable that gets repeatedly created and destroyed.

like image 34
NPE Avatar answered Jan 18 '23 11:01

NPE