jeudi 26 octobre 2017

Needs upper bound in for loop to be saved in extra variable?

I see that often in older code

DWORD num = someOldListImplementation.GetNum();
for (DWORD i = 0; i < num; i++)
{
    someOldListImplementation.Get(i);
}

rather than

   for (DWORD i = 0; i < someOldListImplementation.GetNum(); i++)
   {
        someOldListImplementation.Get(i);
   }

I guess the first implementation should prevent calls to GetNum() on each cycle. But, are there cases that the compiler in C++11 does some optimization to the second code snippet which makes the num variable obsolete?

Should I always prefer the first implementation?

If that question duplicates another question for 100%, tell me and close this one. No problem.

Aucun commentaire:

Enregistrer un commentaire