user877329
user877329

Reputation: 6230

Optimizing member variable access

May C++ compilers optimize the following loop to an infinite loop

this->m_stop=0;
while(!this->m_stop)
    {
//  do stuff
    }

This question is relevant even in a single-threaded context, since a call inside the loop may affect the status flag indirectly.

Upvotes: 0

Views: 80

Answers (3)

Anthony Williams
Anthony Williams

Reputation: 68691

If there is no possible way that the body of the loop can legitimately change m_stop, then this is a permissible optimization.

If the compiler cannot see the contents of the functions in the loop, then it must assume they can change m_stop.

If a pointer or reference to m_stop or *this is stored somewhere accessible to the code that runs in the body of the loop, then the compiler would have to do more extensive analysis to determine whether it is safe to assume m_stop doesn't change. If it cannot do this analysis, then it must assume m_stop may change if the body of the loop changes anything that could potentially refer to m_stop.

Upvotes: 1

TartanLlama
TartanLlama

Reputation: 65770

A compiler can only carry out optimisations which do not affect the observable behaviour of a well-formed program. This is commonly known as the as-if rule; the program must behave as-if it was executed by some abstract machine following the standard to the letter, but an implementation may change things about the execution to make it run faster so long as the program acts in the same way.

As such, the compiler cannot optimise your code into an infinite loop unless it can prove that it doesn't affect the observable behaviour of the program. Of course, if you have undefined behaviour somewhere, then all bets are off.

Upvotes: 1

skyking
skyking

Reputation: 14400

If this->m_stop is non-volatile and the compiler can know that the value of this->m_stop does not alter it's value (ie that the condition will always be true).

Perhaps it could (in some cases) know that the condition will remain true even if this->m_stop is volatile. But still this scenario means it must still basically evaluate at least this->m_stop for each iteration through the loop (even if it knows the result will be 0). Normally a compiler won't know that.

Also the case where this->m_stop alters it value is a possibility if the compiler somehow can know that the value would be 0 at every start of the loop.

Upvotes: -1

Related Questions