• Advertisement
Sign in to follow this  

local variable in long loop

This topic is 4267 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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 :)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement