Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to use static variables in the main function in C?

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?

like image 672
Graafvaag Avatar asked Aug 15 '13 09:08

Graafvaag


2 Answers

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).

like image 113
Ingo Leonhardt Avatar answered Oct 31 '22 18:10

Ingo Leonhardt


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.

like image 31
sh1 Avatar answered Oct 31 '22 17:10

sh1