Sign in to follow this  
derek7

local variable in long loop

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this