Aussie AI
Automatic Array Repeated Initialization
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Automatic Array Repeated Initialization
A simple example of unnecessary double initializations is any type of large local variable,
such as an automatic array.
When a function makes use of a large array variable with constant data, or even a large constant object,
the variable should probably be declared as both “const
” and “static
”, even if it
need not retain its value between calls.
Consider the following code example:
char *convert(int day) { char *days[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; return days[day]; }
The initialization of array “days
” illustrates an inefficiency. The initialization
of “days
” occurs every time the convert function is entered. It would be much more
efficient to declare “days
” as a static
variable
to avoid it being re-initialized, and also “const
” to help the compiler optimize.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |