Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the loop limit be evaluated or stored?

In C++, is it faster to store the limit of a loop in a variable than evaluating the value?

For example:

Is it a slower approach to use

for(int i=0; i<n*n+2*n; ++i)
{ .... }

than doing the following?

for(int i=0, limit=n*n+2*n; i<limit; ++i)
{ .... }

For clarity, assume that n is some given variable that remains unchanged during the course of the loop.

like image 470
Programmer Avatar asked Dec 29 '16 08:12

Programmer


People also ask

Is there a limit to for loops?

In the java for loop, there is no limit. You might be thinking of BASIC. In the java for loop, the 2nd expression is the termination expression. The loop will keep looping for as long as the termination expression is true .

When would you use the while loop?

A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".

How does a while loop work?

The while loop checks the condition first, and if it returns true, the code within it runs. The loop continues until the condition provided returns false, then stops. Alternatively, the do while loop runs its code once before checking the condition and runs again only if the condition is true.

What is while loop in C++ with examples?

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop.


1 Answers

If n is a globally declared non-volatile variable, then the behaviour of

for (int i = 0; i < n * n + 2 * n; ++i)

is unspecified. A compiler is allowed to optimise n * n + 2 * n to be evaluated once even if another thread modifies n. Furthermore, if another thread is able to modify n, then you should take steps to avoid the potential for simultaneous read and writes of n (the behaviour of which is undefined). Consider using std::atomic<int> as the type for n.

So really it's appropriate to introduce limit anyway if you want the stopping condition to be dependent on the value of n observable when program control reaches the for loop, irrespective of any performance considerations. Consider therefore

for (int i = 0, limit = n * n + 2 * n; i < limit; ++i)

which has the advantage that the scope of limit doesn't leak into the surrounding statements.

But if you are able to, you could always run the loop backwards:

for (int i = n * n + 2 * n - 1; i >= 0; --i)

Be very careful though with unsigned types if you adopt that idea.

like image 199
Bathsheba Avatar answered Oct 26 '22 03:10

Bathsheba