sathish
sathish

Reputation: 153

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.

Upvotes: 4

Views: 144

Answers (2)

A.Lymphater
A.Lymphater

Reputation: 73

If this is a real case, you maybe should initialize them explicit.

Upvotes: 0

SteveMinhDo
SteveMinhDo

Reputation: 36

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;
}

Upvotes: 2

Related Questions