meJustAndrew meJustAndrew - 1 month ago 11
C++ Question

Are empty for loops even executed in C++?

I was wondering if the condition inside for loop is always executed if it's a mathematical operation like:

int margin = 100;

for(int i=0; i<margin/2;i++);//is margin divided by two at every cycle?


so I have written the following program:

long margin = 1000000000, halfOfMargin = margin/2;
clock_t begin_time;
clock_t stop_time;

for(long j=0;j<10;++j)
{
begin_time = clock();
for(long i=0;i<margin/2;i++);
stop_time = clock ();

cout <<"With margin/2 :"<< float( stop_time - begin_time ) / CLOCKS_PER_SEC<<"\n";
}
for(long j=0;j<10;++j)
{
begin_time = clock();
for(long i=0;i<halfOfMargin;i++);
stop_time = clock ();
cout <<"With halfOfMargin :"<< float( stop_time - begin_time ) / CLOCKS_PER_SEC<<"\n";
}


to test the two methods separately, (sorry for the messy code).

I have concluded that in Debug configuration the divide version is even faster than the second aproach. What surprised me was that when I switched to Release, I got the output of 0 for each of the versions every time, which would have been imposible if the
for
instructions were actually executed (in Debug configuration the time of each output was about a second and a half).

My question is that if it is possible to be skiped instructions by the compiler if it finds them unnecesary, and if not why the times were so different for those two cases?

Note: I am using Visual Studio 2012 express as an IDE with the default compiler.

Answer

The C++ standard describes the behavior of an abstract machine.

Certain parts of its behavior are externally observable.

Any behavior whose effects are not observable can be skipped under what is known as the "as-if" rule.

That means the compiler is free to skip useless code. In some situations, it can even skip an infinite loop by proving that it changes nothing anyone could spot, set the state to be what would permit the loop to exit, and exit the loop.

In "debug", compilers tend to optimize far less.