简体   繁体   中英

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. (fi 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.

我认为当你为他们制作包含许多文件和主管的交流项目时,它的价值不会改变....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM