• recategorized by
2,084 views
1 1 vote

 
  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

3 Answers

4 4 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 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 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
Position:
Show:

Related questions

3 3 votes
1 1 answer
1.5k
1.5k views
rahul sharma 5 asked Nov 23, 2017
1,458 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...
6 6 votes
2 2 answers
201
201 views
GO Classes asked Jun 12
201 views
What will happen when the following code is compiled?#include <stdio.h int x = 5; int main() { extern int x; int x = 10; printf("%d", x); return 0; }$\texttt{5}$ $\texttt...
7 7 votes
2 2 answers
219
219 views
GO Classes asked Jun 11
219 views
What is the output of the following code?#include <stdio.h int x = 10; int main() { int x = 20; { extern int x; printf("%d", x); } return 0; }$\texttt{10}$ $\texttt{20}$ ...
10 10 votes
3 3 answers
308
308 views
GO Classes asked Jun 11
308 views
Given the following three files, what will be the output after compiling and linking them together?file1.cextern int i; void f() { i++; }file2.cint i = 0; void f(); void ...