0

I have this really weird doubt in extern usage

Consider the code

#include<stdio.h>

int main(void)
{
extern int a;
printf("%d",a);

getch();
return 0;
}
int a=20;

How is it that this code gives the output as 20 ???


My guess
Since its an extern variable, it can be declared anwhere( even outside the main).
Since its the same file, we dont have to do a #include"samefile.h"

Please correct me...

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by Narue
0

extern means the variable may be declared in another source file or later in the same source file. See the remarks here

Also, the value of global variables are set before main() is called, which is why printf() can display the correct value of that variable.

Edited by Ancient Dragon: n/a

0

Since its the same file, we dont have to do a #include"samefile.h"

Since headers provide declarations, and the extern declaration already does that, including a header at all is unnecessary. You can still have two files:

/* foo.c */
int a = 20;
/* main.c */
#include <stdio.h>

int main(void)
{
    extern int a;

    printf("%d\n", a);

    return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.