retagged by
1,410 views
2 votes
2 votes
extern int i;
int i = 10;
i = 5;
int main() { 
printf("%d", i); 
return 0;
}

The output for the above code is _______

retagged by

2 Answers

Best answer
0 votes
0 votes
  • A variable is declared when the compiler is informed that a variable exists (and this is its type); it does not allocate the storage for the variable at that point.
  • A variable is defined when the compiler allocates the storage for the variable.

Declaration can be done any number of times but definition only once. 

As extern is used with a variable, it’s only declared not defined.

extern int i; // Here, memory is not allocated for this variable. 
int i = 10; //Here, memory is allocated for this integer variable (it's definition with initialization). 
i = 5; // As declaration is already done, here "i" is defined again which is invalid. 

It will throw error here. 

For more information on "extern" keyword:

1. https://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

2. https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files

selected by
2 votes
2 votes

@MiNiPanda  Definition declares a variable and causes the storage to be allocated. For example:

int x = 10;         /* x is declared as an integer and allocated space and initialized to 10 */
    int roll_no[100];   /* roll_no is declared as an array of integers, allocated space for 100 integers *

 Declaration specifies the properties of a variable. For example:

  int x;              /* x is an integer */
    int roll_no[];      /* roll_no is an array of integers */

Related questions

0 votes
0 votes
1 answer
1
Na462 asked Nov 19, 2018
1,443 views
1 votes
1 votes
0 answers
2
2 votes
2 votes
1 answer
3
rahul sharma 5 asked Nov 23, 2017
1,033 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...