Why some people do:
char baa(int x) {
static char foo[] = \" .. \";
return foo[x ..];
}
instead of:
char baa(int x) {
In typical implementations, the version with static
will just put the string somewhere in memory at compile time, whereas the version without static
will make the function (each time it's called) allocate some space on the stack and write the string into that space.
The version with static
, therefore,
foo
is something bigger).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.
Defining a variable static in a method only means that the variable is not "released", i.e. it will keep its value on subsequent calls. It could lead to performance improvement depending on the algorithm, but is certainly not not a performance improvement by itself.
Yes, the performance is different: unlike variables in the automatic storage that are initialized every time, static variables are initialized only once, the first time you go through the function. If foo
is not written to, there is no other differences. If it is written to, the changes to static variables survive between calls, while changes to automatic variables get lost the next time through the function.
Yes it makes difference , if u have declared a variable as static :
Firstly, the memory will be allocated in either bss or data segment instead of stack.
Secondly, it will be initialized for once only , not every time unlike other variables of function, which will surely create difference.
Thirdly, it retains it's value b/w function calls.So depending on the situations you should use it.