This is something I've always been curious about. Is the variable pushed only once when the loop starts and then popped when it breaks, or pushed and popped after every iteration?
Since it would have a performance penalty, I'll do a little benchmark:
#include <iostream>
#include <ctime>
#define N 1000000000
int main(){
unsigned t0,t1;
t0=clock();
for (unsigned a=0;a<N;a++){
unsigned b=a;
b++; //Added just in case the optimizer decided an empty loop was better
}
t1=clock();
std::cout <<"time for inner declaration: "<<t1-t0<<" ms"<<std::endl;
t0=clock();
unsigned b;
for (unsigned a=0;a<N;a++){
b=a;
b++;
}
t1=clock();
std::cout <<"time for outer declaration: "<<t1-t0<<" ms"<<std::endl;
return 0;
}
Output for unoptimized: time for inner declaration: 5953 ms
time for outer declaration: 5937 ms
Output for optimized: time for inner declaration: 547 ms
time for outer declaration: 547 ms
Outer declaration is 0.27% faster than inner declaration.
Conclusion: There is no penalty.
With a good optimizing compiler, the loops should be equivalent, in that the stack space is allocated only once, as opposed to once each iteration.
This does not apply to non-POD types with non-trivial constructors/destructors, however, as in those cases, the constructor and destructor will be called each iteration.