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...

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.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.