As far as my current understanding of the 'static' keyword goes, it prevents a variable from being re-initialized AND it prevents the variable from leaving the memory when a function ends.
In C, I usually use this when a variable doesn't need to be global, but also shouldn't change in between function calls. (f.i. microcontroller interrupts)
Now, in some C code for an STM32, I saw the following:
int main(void)
{
static char buffer[CONSOLEBUFFERSIZE];
...
To me, this doesn't make sense. This variable is used to buffer incoming commands in order to process them when the termination character is received. But the two properties of 'static' I described earlier do not apply to the main function because main() is called only once and 'never' ends. So my actual question:
Could this be using some hocus-pocus that I don't know about or would it simply be copied code from an interrupt or other function and did the programmers forget or not bother to remove the static keyword?
One difference is, that static variables usually use the program's data segment instead of stack. Maybe that's the reason for declaring buffer
as static
(especially if CONSOLEBUFFERSIZE
is large).
On some systems the stack is a fixed, limited size. In these cases static
is useful simply to move the buffer out of the stack and put it somewhere where the linker has been set up to allocate more space.
It would also be possible to re-configure the linker to offer a larger initial stack, but static
is easier and still does the right thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With