简体   繁体   中英

Simple For Loop C++ why

I am just wondering why I would do this in c++

for(int i=0, n=something.size(); i<n; ++i) 

vs

for(int i=0; i<something.size(); ++i)      

..

Assuming syntactically correct versions of both samples, if the call to something.size() were expensive, the first sample would potentially be more efficient because it saves one call per loop iteration. Even so, you should measure whether it actually makes a difference.

Note that the two would have different semantics if the size of something were to change inside of the loop.

The loop condition is evaluated before every loop round, so if the operand of the comparison doesn't change (ie you don't mutate the sequence during its iteration), then you don't need to recompute the operand each time and instead hoist it out.

Whether that makes a difference depends on how much the compiler can see of the size() call. For instance, if it can prove that the result cannot change during the iteration, then it may already do the hoisting for you. If in doubt, compile both versions and compare the machine code.

If you do

for(int i=0; i<something.size(); ++i);

it will be correct. You should check in some C++ handbook how for loop looks like. Your second example is invalid C++ code

The two examples are not the same.

for(int i=0, n=something.size(); i<n; ++i)
{
    // ....
}

evaluates something.size() only once.

for(int i=0; i<something.size(); ++i)  // Syntax corrected 
{
    // ....
}

evaluates something.size() in each loop.

So they could behave very differently if something.size() changed while doing the loop.

If you know something.size() will not change, you should go for the first solution for performance reason (ie only one call to something.size()).

If something.size() can change (eg in the body of the for-loop) the second option is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM