Aussie AI

Exit loops and functions early

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

Exit loops and functions early

Control structures should be exited as soon as possible, including function paths and loops. This means judicious use of return for functions and break or continue for loops.

Using “return” as early as possible in a function is efficient. It prevents unnecessary code being executed. Testing for edge cases at the start of a function is an example of using the return statement to do “easy cases first” or “simple cases first” optimizations.

Exit loops early. Similarly, both break and continue are efficient, as no more of a loop is executed than is necessary. For example, consider the code using a Boolean variable “done” to indicate the end of the loop, as in:

    done = false;
    while (!done) {
        ch = get_user_choice();
        if (ch == ’q’)
            done = false;
        else
            ... // rest of loop
    }

The faster code has a break statement used to exit the loop immediately:

    while (1) { // Infinite loop
        ch = get_user_choice();
        if (ch == ’q’)
            break; // EXIT EARLY!
        else
            ... // rest of loop
    }

Unfortunately, the overuse of jump statements such as break and continue can make the control flow of a program less clear, but professional C++ programmers are used to these statements being used often.

 

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++