Why some people do:
char baa(int x) {
static char foo[] = \" .. \";
return foo[x ..];
}
instead of:
char baa(int x) {
It's not for performance per se, but rather to decrease memory usage. There is a performance boost, but it's not (usually) the primary reason you'd see code like that.
Variables in a function are allocated on the stack, they'll be reserved and removed each time the function is called, and importantly, they will count towards the stack size limit which is a serious constraint on many embedded and resource-constrained platforms.
However, static variables are stored in either the .BSS
or .DATA
segment (non-explicitly-initialized static variables will go to .BSS
, statically-initialized static variables will go to .DATA
), off the stack. The compiler can also take advantage of this to perform certain optimizations.