extern keyword usage

Viewed 13967

I have three programs in which I am using extern keyword. I am not able to understand the result. Below are three examples:

Example 1: I was expecting that below code will give compilation error that multiple declaration of k. But it works fine?

int k; //works fine
extern int k = 10;

void main()
{
    cout<<k<<endl;
    getchar();
}

Example 2: When I am trying to initialize "k" in above example compiler gives error. Why?

int k = 20; //error
extern int k = 10;

void main()
{
    cout<<k<<endl;
    getchar();
}

Example 3: In this example I changed the order of definitions mentioned in example 1. When I compile this code I am getting errors. Why?

extern int k = 10;
int k;   //error

void main()
{
    cout<<k<<endl;
    getchar();
}
9 Answers
Related