1

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?

1
  • 5
    Static variable initialization only happens the first time the function is called. Commented Dec 24, 2021 at 18:44

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

C 2018 5.1.2 1 says “All objects with static storage duration shall be initialized (set to their initial values) before program startup”, emphasis added.
This answer is only half-correct. Please update it or delete it.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.