Jump to content

Initializing Variable Within a Loop

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
sourlemon

sourlemon

    Programmer

  • Members
  • PipPipPip
  • 99 posts
Suppose I have this loop statement:

int x = 0;
while (x < 5){
    int y = x++;
}    

Does this mean the variable y is initialize every time we go through the loop? Or does it mean the variable y is not pop off the stack until the loop end? To put it simply, is it faster to declare y inside or outside of the loop, given that I won't use y outside of the loop?

#2
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
variable y is initialized on each loop iteration. But in the case you posted it won't matter whether y is declared inside or outside the loop because of the assignment operator =. In c++ you normally declare variables in the scope in which they are used -- meaning inside the loop in your case since you will not use it outside the loop. The code you posted is perfectly acceptable, although I guess you would write more code that uses variable y.

>>Or does it mean the variable y is not pop off the stack until the loop end?
Initializing a variable and popping it off the stack are two entirely different things. Although it might depend on the processor type, on Intel based computers all variables are actually allocated on the stack upon function entry even though they may be declared later on in the C++ code. That's because of the way the Intel based assembly language works. Other processor types, such as RISK might do it differently.

So the answer to your question is ---- maybe yes and maybe no.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.