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.

  • `Is static is like global variable.` No!!!! it's same in terms of life time.different in terms of visibility. – Jayesh Bhoi Sep 01 '14 at 06:20
  • Please fix the syntax errors first and then go to the philosophical questions :) – Hanky Panky Sep 01 '14 at 06: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. – Some programmer dude Sep 01 '14 at 06:21
  • Also that code has an endless loop, please work on those things first – Hanky Panky Sep 01 '14 at 06: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). – Jonathan Leffler Sep 01 '14 at 06:27

2 Answers2

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
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!

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sathish
  • 3,740
  • 1
  • 17
  • 28