recategorized by
1,058 views
0 votes
0 votes

 
  1. int main()
  2. {
  3. extern int a = 20;
  4. printf("%d",a);
  5.  
  6. }
  7. //why this gives error but followig code is not
  8.  
  9. extern int a =20;
  10. int main()
  11. {
  12. printf("%d",a);
  13.  
  14. }
  15.  
  16. //why this happens that first code gives error but second is not ?
  17. //please tell i am realy confused now
recategorized by

3 Answers

2 votes
2 votes

Both the codes are not correct in C. 

arjun@Armi:~$ gcc -O1 a.c
a.c:2:12: warning: ‘a’ initialized and declared ‘extern’
    2 | extern int a = 20;
      |            ^

Just that in the second case since “initialization” of an extern variable is done outside of any function, memory is allocated statically (before any function gets executed) and so the code works ignoring “extern”, albeit with a warning. If “-Werror” parameter is given as in most production codes, this will turn to an error. In other words “initialization” should not be done while using “extern”. 

0 votes
0 votes
Hii @ykrishnay

Since you are defining and declaring extern variable together (extern int x=12) inside the function which is not permissible in C.we can only declare extern variable inside the functions by using extern keyword.
edited by
0 votes
0 votes
First we need to understand the simplication of extern int a = 20;

So we can write this as

extern int a; (1)

int a = 20;     (2)

So in first program this simplication will happen but now compiler is confused because (1) is telling some a variable present globally take value from that (2) is telling take my value so compiler is confused between this 2 values so it will produce compiler error

In second program since this simplication is happening outside a Function (1) is telling some a variable present globally don't worry (2) is telling I am the only global variable which is pointed by (1) so a will have global variable value 20 here will be no confusion and program will print a as 20

Related questions

2 votes
2 votes
1 answer
1
rahul sharma 5 asked Nov 23, 2017
1,055 views
#include <stdio.h int main() { int a=10; extern int a; return 0;} Why this gives compilation error? Extern is just a declaration.So why it is giving error on c...
2 votes
2 votes
2 answers
4
Rohan Mundhey asked Nov 5, 2016
3,612 views