Home > database >  C static variables initialization
C static variables initialization

Time:12-25

I learned some C and came across an explanation for static variables. They showed this code:

#include<stdio.h>
int fun()
{
  static int count = 0;
  count  ;
  return count;
}
  
int main()
{
  printf("%d ", fun());
  printf("%d ", fun());
  return 0;
}

I can't understand why calling the function twice is fine, because the line

static int count = 0;

actually runs twice... I can't understand how is that possible... Can you actually declare it twice or does the compiler just ignore it the second time?

CodePudding user response:

This (statics/globals) is where an initializing definition is really different from an uninitialized definition followed by an assignment. Historically, the former even used to have different syntax (int count /*no '=' here*/ 0;).

When you do:

int fun() {
  static int count = 0;
  //...
}

then except for the different scopes (but not lifetimes) of count, it's equivalent to:

static int count = 0; //wider scope, same lifetime
int fun() {
  
  //...
}

In both cases, the static variable becomes initialized at load time, typically en-masse with other statics and globals in the executable.

CodePudding user response:

static variables are initialized on program startup, not every time the function is called.

CodePudding user response:

... because the line static int count = 0; actually runs twice.

No. Just once, right before main() is called.

  • Related