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 |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |