Why do some people declare make their variables static, like so:
char baa(int x) {
static char foo[] = " .. ";
return foo[x ..];
}
instead of:
char baa(int x) {
char foo[] = " .. ";
return foo[x ..];
}
It seems to be very common on Linux source codes applications. Is there any performance difference? If yes, might someone explain why? Thanks in advance.
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.