What actually compiler does when we declare static variables?

后端 未结 4 1603
既然无缘
既然无缘 2021-01-05 07:58

I want to know what actually going under the hood,how compiler treats static variables. Unlike auto variable, static variable\'s value persist even after the end of block bu

4条回答
  •  轮回少年
    2021-01-05 08:40

    static variables are global variables with limited scope. @user3386109

    1. static/global variables exist for the lifetime of the program.
    2. static/global are initialized at program start-up to either:

      A. If not explicitly initialize: to the bit pattern 0.
      B. Otherwise to to an explicit value like double x = 1.23;

    3. static variables scope is either limited to

      A. If defined outside a function: file scope, only code within the file can "see" the variable.
      B. If defined inside a function: block scope: only code within the block may "see" the variable.

    4. There is only one instance of the static variable within its scope unless a lower scope defines another with the same name. The compiler "knows" which same named variable to access by using the closest scope first. It is not re-created or re-initialized, even if inside a function.

    Note: With multiple threads, other considerations apply - not shown.

    static int fred = 11;
    int sally = 21;
    
    void foo2(void) {
      static int fred = 31;
      int sally = 41;
      printf("static %d non-static %d\n", fred++, sally++);
      {
        printf("static %d non-static %d\n", fred++, sally++);
        {
          static int fred = 51;
          int sally = 61;
          printf("static %d non-static %d\n", fred++, sally++);
        }
      }
    }
    
    int main(void) {
      printf("static %d non-static %d\n", fred++, sally++);
      foo2();
      printf("static %d non-static %d\n", fred++, sally++);
      foo2();
      return 0;
    }
    

    Output

    static 11 non-static 21
    static 31 non-static 41
    static 32 non-static 42
    static 51 non-static 61
    static 12 non-static 22
    static 33 non-static 41
    static 34 non-static 42
    static 52 non-static 61
    

提交回复
热议问题