-3
extern int i;
void add();

int main()
{
    add();
    if (i == 0)
        printf("scope rules\n");
}

void add()
{
    int i;
}

I getting error in this case even variable i is defined in add function

but it will give no build errors in following case

extern int i;
void add();

int main()
{
    int i;
    //add();
    if (i == 0)
        printf("scope rules\n");
}

void add(){
    //int i;
}
Ahmad Khan
  • 2,655
  • 19
  • 25
ravi
  • 63
  • 1
  • 8

1 Answers1

2

The extern keyword tells the compiler to assume that the variable is defined elsewhere (not in this particular file or translation unit). The name of the variable will be resolved at linking stage.

So when you write:

extern int i;

you must make sure that variable i is defined elsewhere (in a different file).

And beware not to confuse that extern i and the local i in your add function - this local variable has scope inside the add function and has nothing to do with the extern i variable.

void add()
{
    int i;
}
artm
  • 17,291
  • 6
  • 38
  • 54