user3180902
user3180902

Reputation:

what is the difference between the two codes?

this is the first code

#include <stdio.h>
void a();
int i;
int main()
{
    printf("%d\n",i);
    a();
    return 0;
}
int i=5;
void a()
{
printf("%d\n",i);
}

output

5
5

the second code is

#include <stdio.h>
void a();
extern int i;
int main()
{
    printf("%d\n",i);
    a();
    return 0;
} 
int i=5;
void a()
{
     printf("%d\n",i);
}

ouput

 5
 5

what is the difference between the codes if their outputs are same... and if they are same then what is the use of extern

Upvotes: 0

Views: 89

Answers (2)

KARTHIK BHAT
KARTHIK BHAT

Reputation: 1420

extern is something like saying to the Linker that you have defined the variable in some other file( even global variables can be made extern inside other functions in same file) don't throw error now you will find the variable later then link it .

using extern your only declaring the variable not defining it(no memory allocated).

In Your second program for first declartion

        extern int i;

No memory is allocated but later when you declare

     int i = 5 ;

the memory is allocated for i. while linker searches for i in printf if i is not declared extern it throws a error since its extern linking takes place when it finds the defintion of i.

Upvotes: 1

mikea
mikea

Reputation: 6667

extern means that you are declaring the variable but not defining it (allocating memory for it). Have a look at this link for a good explanation of extern: http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

Upvotes: 0

Related Questions