3
#include <stdio.h>
 
void f (void)
{
    static int count = 0;   // static variable   
    int i = 0;              // automatic variable
    printf("%d %d\n", i++, count++);
}
 
int main(void)
{
    for (int ndx=0; ndx<10; ++ndx)
        f();
}

For example, in this code, where is count stored? Usually, static variables will be stored in the Data segment, and local variables are stored on the stack.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    It has "static" storage just like global variables. – Ben Voigt Sep 13 '21 at 15:47
  • you can read linker manual or ld file to see where your data goes to, eg: static to section .bss, while const types to .rodata. while .stack only specifies the area and size of stack – JosiP Sep 13 '21 at 15:58
  • Dupe? [**Where do static local variables go**](https://stackoverflow.com/questions/16703886/where-do-static-local-variables-go?rq=1) – Andrew Henle Sep 13 '21 at 16:49

1 Answers1

7

Formally, variables declared inside of a function as static have static storage duration, which means their lifetime is the lifetime of the entire program.

The C standard says nothing about stacks or segments as those are implementation details. That being said, on Linux initialized static variables are typically placed in the .data section while uninitialized or 0 initialized variables are stored in the .bss section.

dbush
  • 205,898
  • 23
  • 218
  • 273