1,116 views
2 votes
2 votes


#include<stdio.h>
int i=5;
int main()
{
  extern int j;
  printf("\ni=%d \nj=%d",i,j);
  int j=10;
  return 0;
}


OUTPUT:-


i=5
j=10

but when i compile this code ,i get compilation error 

source of question is http://cprogrammingcodes.blogspot.in/2012/02/external-storage-class.html

please explain what,s wrong

1 Answer

3 votes
3 votes

Output and explanation in the link you provided are wrong!

  • extern declaration specifies that the variable j is defined somewhere else.  
  • The compiler passes the external variable to be resolved by the linker. 
  • So compiler doesn't find any error.
  • During linking the linker searches for the definition of j.
  • Since it is not found the linker flags an error

#include<stdio.h>

int i=5;
int main()
{
  extern int j;
  printf("\ni=%d \nj=%d",i,j);
 
  return 0;
}

 int j=10;  // define j outside main() block.! So linker successfuly finds definition and prints value!

Related questions

0 votes
0 votes
1 answer
2
Desert_Warrior asked May 16, 2016
2,354 views
#include<stdio.h int main() { int a = 5; int b = ++a * a++; printf("%d ",b); return 0; }(a) 25 (b) 30 (c) 36 (d) Undefined Behavior
0 votes
0 votes
2 answers
3
Desert_Warrior asked May 16, 2016
8,899 views
#include<stdio.h int main() { int a = 5; switch(a) { default: a = 4; case 6: a ; case 5: a = a+1; case 1: a = a-1; } printf("%d \n",a); return 0; }(a) 5 (b) 4 (c) 3 (d) N...