Aussie AI

Incorrect choice of loop

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

Incorrect choice of loop

Although the choice of loop is largely a matter of style, there is an important difference between the post-tested “do” loop, and the pre-tested “for” and “while” loops. The loop condition of a do-while loop is not evaluated on the first iteration and the loop body is always executed at least once. However, a for or while loop condition is evaluated before the first iteration and the loop body need not be executed at all. A common form of minor inefficiency is declaring loops that are always executed the first time, such as:

    bool done = false;
    while(!done) {
        // ....
    }

It is more efficient to use the do loop, which avoids a single evaluation of the loop condition:

    bool done = false;
    do {
        // ....
    } while(!done);

The use of the correct type of loop is also helpful to the optimizer. It is valuable to know that a code segment is always executed once.

Infinite loops are control flow structures that can also be detected and used by the optimizer. Hence, you should code an infinite loop explicitly by using one of the common idioms:

    for(;;)       // Forever
    while(1)      // Common
    do..while(1)  // Not commonly used

This allows the compiler to generate efficient code, because you've made it easy for the compiler to recognize the loop as infinite.

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++