Search code examples
cstaticdata-segment

C data segment identification


If I declare

  static int a ;// globally and 
  static int a ; // locally in one function 

So now there are two instances of a ..

I know all static variables goes into data segment but how they are differentiated in data segment which one is local and which one is global ??


Solution

  • You can in fact go further: you can declare

    static int a;
    

    at file scope in two or more separate files contributing to your program. Each such declaration in a different scope declares a separate variable. Thus, given

    f.c:

    static int a;
    
    int f() {
        static int a;
        return 0;
    }
    

    main.c

    static int a;
    
    int f(void);
    
    int main() {
        return f();
    }
    

    There are three separate static variables associated with the name a in different places. It is the compiler and linker's job to arrange for the correct storage to be associated with each variable reference.