Monday, February 5, 2018

Coding using keywords- part 6 (extern)

You can see all the keywords in C in this link: https://philippebalech.blogspot.com/2018/01/keywords-in-c.html

extern keyword is usually defined by default with the compiler without the need to set it before any data type. For example:

  1. #include <iostream>  
  2. using namespace std;  
  3. int i;    //By default it is extern variable  
  4. int main(){  
  5.     cout<<"The value of i is :"<<i;  
  6.     return 0;  
  7. }  

The compiler will automatically set extern before int i.
This case is also implemented for functions.



As you can see in the picture, extern main use is to tell the compiler that the variable I'm pointing on is declared in different function, place or even source code. Let's take an example:

  1. #include <iostream>  
  2. using namespace std;  
  3. char character;int decimal;double fraction;char *pointer;  
  4. int main(){  
  5.     extern int variable; //Search for the initialization of variable outside the main  
  6.     cout<<"Variable = "<<variable;  
  7.     cout<<"\nValue of character :"<<character  
  8.         <<"\nValue of decimal number :"<<decimal  
  9.         <<"\nValue of fraction number :"<<fraction  
  10.         <<"\nValue of pointer :"<<pointer;  
  11.     return 0;  
  12. }  
  13. int variable=30;    //Initialization of variable i.  

Output:

Variable = 30
Value of character :0
Value of decimal number :0
value of fraction number :0.00...
Value of pointer : (null)

Explanation


By using extern in the first line inside the main, I told the compiler that (variable) is initialized outside the local function (main); the compiler will search on the variable inside and when finds the value so the output will be 30. If you look on the output, you'll also see that the values of character, decimal, fraction (variables) are 0, 0, 0.00 as many zeros as the size of double in RAM. In addition, the value of the pointer is null. The reason behind this is that the compiler set all these variables to extern and will give those types (int, double, char) 0 as a default value. And for any pointer, it'll give it a default value of null because it's pointing on nothing.

No comments:

Post a Comment