Search code examples
cmemorymemory-managementcompiler-errorsstatic-variables

Static variables local to function


I am learning storage classes in C.I have a simple code

enter code here
int f1()
{
    static int i=0;
    i++;
    printf("%d",i);
}

int f2()
{
    printf("%d",i);
}

int main()
{
    f1();f2();f1();f2();
}

Compiler gives error as 'i' is undeclared in f2(). As I thought,memory static variables are allocated in data section of program memory.So any function in that file should be able to access it.

How does compiler knows that variable locally declared in function is bounded to that function only?How compiler evaluates that?


Solution

  • Although the lifetime of static variable isn't tied to the scope where it is defined (unlike variables with automatic storage duration):

    {
        static int i=0;
        i++;
        ...
        {
            i++;  // <-- still well defined, even in nested scope
        }
    }
    i++;  // <-- undefined
    

    it is accessible only within this scope. The compiler just checks whether the symbol i has been defined before and it sees, that i has not been defined within that scope (the static int i=0; defines a variable that is accessible locally ~ compiler doesn't care about its lifetime).

    In case you need it to be accessible out of its scope, you'll have to pass it out of it by reference (its address) or make it global:

    static int i = 0;
    ...
    {
        i++;
    }
    ...
    i++;  // <-- accessing global variable