extern keyword is usually defined by default with the compiler without the need to set it before any data type. For example:
- #include <iostream>
- using namespace std;
- int i; //By default it is extern variable
- int main(){
- cout<<"The value of i is :"<<i;
- return 0;
- }
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:
- #include <iostream>
- using namespace std;
- char character;int decimal;double fraction;char *pointer;
- int main(){
- extern int variable; //Search for the initialization of variable outside the main
- cout<<"Variable = "<<variable;
- cout<<"\nValue of character :"<<character
- <<"\nValue of decimal number :"<<decimal
- <<"\nValue of fraction number :"<<fraction
- <<"\nValue of pointer :"<<pointer;
- return 0;
- }
- 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