in Programming in C retagged by
1,491 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 _______

in Programming in C retagged by
1.5k views

4 Comments

@Mk Utkarsh and @sumit goyal 1

https://www.cprogramming.com/declare_vs_define.html

I guess I had the wrong idea of declaration, definition and initialization. The source from where I read was not good I think. Please check this link and verify whether this one is right or not.

0
0
it is correct. any point in this article you find contradicting?
0
0
No.. you are correct...I am studying about  extern from geeksforgeeks now :p
1
1

2 Answers

0 votes
0 votes
Best answer
  • 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 */

3 Comments

edited by

@MiNiPanda   i=5;  // should be called assignment

0
0
I understood your answer and agree with it :) ..but the comment part.. x=5 is initialization?
1
1

@MiNiPanda  i think it should be called assignment  thanks

0
0