local variable in long loop

Started by
1 comment, last by JohnBolton 17 years, 11 months ago
for (long loop) { int i// should it put loop outside? use(i); std::vector<type> arc(1000);// should it put loop outside? ofstream of("filename", ios_base::binary); of.write(....)// how about it? } so my question: what local variable should be put loop outside to prevent repeatly created
Advertisement
As far as the POD types, you can declare multiple variables in a for loop, whilch will only be available within the scope of that loop according to the new standard.

for(int i,j,k=0;k<10;++k){//create once
//use i,j, and k here
}
//but not here

Regarding the other stuff, you could also always dynamically allocate them before use in the loop and then delete them afterward......I guess. Not an expert here, just giving it a shot. There could be optimizations made by the compiler, too. Maybe a compiler honcho could clear that up, but I answered part of it, anyway :)
______________________________Stranger things have happened...The Following Sentence is True. The Above Sentence is False.
Quote:Original post by Photonman
for(int i,j,k=0;k<10;++k){//create once
//use i,j, and k here
}
//but not here

While you can do this, it is not a good idea. It is better to declare i and j inside the loop -- mostly because it is not confusing.

To answer the OP's question -- a variable should be declared in the scope in which it is used. Since the variable i is only used inside the loop, it should be declared inside the loop. Any intrinsic type or any type with a trivial constructor can be declared inside the loop with little or no performance penalty. However, you might declare arc and of outside the loop to improve performance. Keep in mind that this has initialization implications since a variable declared inside the loop will be constructed every iteration, but a variable declared outside the loop will be constructed once.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!

This topic is closed to new replies.

Advertisement