Search code examples
cvariablesinitializationstatic-variables

Initialization for static variables


static int i = 5;
static int j = i;

int main()
{
    return 0;
}

I am initializing the static variable by another static variable which is declared before that but also I am getting variable. Please tell me why this is error.


Solution

  • You cannot initialize j with i, because at compile time, compiler will not know the value of i.To assign the value j = i, the code need to be executed at run time. When initialize the global or static in C, the compiler and linker need to work together to create the layout of memory. Compiler will give the value and linker need to give the address of the variable. The below code will work:

    static int i = 5;
    static int j;
    
    int main()
    {
        j=i;    
        return 0;
    }