0

I have a simple question about static variables. If I declared a static variable in a function:

void main() { int k = 0 while(k<=4) { fun(); k++; } } int fun() { static int i=5; i++; printf(Value %d\t", i); return 0; } 

As I know, the function will deallocate after returning. But where is the i value stored. Is a static variable like a global variable.

5
  • Is static is like global variable. No!!!! it's same in terms of life time.different in terms of visibility. Commented Sep 1, 2014 at 6:20
  • Please fix the syntax errors first and then go to the philosophical questions :) Commented Sep 1, 2014 at 6:21
  • 1
    The C specification doesn't say where variables have to be stored, just that a local static variables lifetime is over the whole program. However, compilers usually store local static variables together with global variables. Commented Sep 1, 2014 at 6:21
  • Also that code has an endless loop, please work on those things first Commented Sep 1, 2014 at 6:22
  • 1
    'Tis curious that you have void main() which is non-standard and only valid on Microsoft Windows with a Microsoft C compiler, and you have int fun() and don't use its return value. It would be more orthodox to have int main(void) and void fun(void) — though you'd have to define or declare fun() before main() if you changed its signature (though C89 compilers such as MSVC don't mind about the implicit int rule for functions, but that's a 25-year old standard and the 15-year old C99 standard outlawed implicit declarations for functions). Commented Sep 1, 2014 at 6:27

2 Answers 2

3

The function will not deallocate i inside fun() on return. The storage for i is in the same general area as global variables — but it is not a global variable. It is only accessible inside the function fun() where it is defined. It is separate from any global variable i or any other variable i that is static inside any other function (in any source file), or from a file scope static variable i in the source file where fun() is defined. It has a lifetime as long as the program.

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

Comments

1

As I know, the function will deallocate after returningNo. I think your assumption is wrong!

static variables won't be deallocated after returning from the function.

Where is it stored?static variables are stored in "Data Section" or "Data Memory".

Life — The life of the static variable starts when the program is loaded into RAM, and ends when the program execution finishes!

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.