in Programming in C recategorized by
1,010 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
in Programming in C recategorized by
1.0k views

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

by
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

3 Comments

I got it but why this gives error what is the logic of this 1st code that would give error basically why we not declarw and define in a function but outside function, no problem easily compileble why this is so?

Please help for this question.

 

Thanks for answering
0
0
Variable declaration with extern keyword always refer to the global variable since you also have  same name local variable in the same function compiler will not able to access global variable and gives an error.

 

Sample Program

---------------------------------------------------------------------------------------------------------------------------

int x=10 // global variable

main(){

extern int x; //variable declaration which always refer to the global variable x but due to local variable x compiler will not able to access global variable.

int x=15 //local variable

}
0
0
What if we do this?

Main {

Extern int x = 10;

Printf ("%d", x) ;

Int x = 20;

}
0
0

Related questions

2 votes
2 votes
2 answers
4
Rohan Mundhey asked in Programming in C Nov 5, 2016
3,611 views
Rohan Mundhey asked in Programming in C Nov 5, 2016
3.6k views