-1

With static in C one can keep a stack variable around, even after the creating function exists.

In this case however,

void static_func() {
    static int var = 1;
    var += 1;
}

I can access var outside of the static_func() and return its value. Let's assume static_func() is called three times in the main(), then the value of var is 3.

However, it is set to 1 every time the function is executed. Why do I still get the value 3?!

12
  • static and static variables mean something different. Commented Jun 2, 2016 at 14:38
  • 3
    "However, it is set to 1 every time the function is executed." Why? Because your compiler contains a bug? Commented Jun 2, 2016 at 14:38
  • 2
    And where is your stack? This is no keyword in C, nor does C require a stack. And typical implementations which use a stack don't store static variables (which are a subset of static variables) on the stack. Commented Jun 2, 2016 at 14:39
  • @MikeCAT I do not hope so! ;) Commented Jun 2, 2016 at 14:43
  • 1
    "I can access var outside of the static_func()" - If that is true, instantly rm -f $YOUR_COMPILER_BINARY_WITH_PATH. And (1 + 3 * 1) == 4, not 3. Commented Jun 2, 2016 at 14:45

2 Answers 2

6

Once you say static int var = 1;, this variable is created and initialized. This can happen only once, otherwise you're gonna flood your memory with useless duplicates since this variable will stay alive during whole program runtime.

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

Comments

4

The initial value of a static variable is only applied once at program startup. It doesn't happen each time the function is entered.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.