Tuesday, June 12, 2012

Concept of global and global declaration

//program to illustrate the concept of global variable
#include <iostream>
using namespace std;

int myint;       //this is the declaration of global variable

void another_function()
{
    myint = 12345;
}

int main()
{

    cout << myint << endl; 

    myint = 10;
    cout << myint << endl;
 

    another_function();
    cout << myint << endl;
}


output:
0                         //because cpp compiler define global variable to 0; if they r not declared
10
12345 
_______________________________________________________________
//program to illustrate global declaration concept
#include <iostream>
using namespace std;

struct int_holder
{
    int my_int1;
    int my_int2;
    double my_double;
};

int main()
{
    int_holder holder;
    cout << holder.my_int1 << endl;
    cout << holder.my_int2 << endl;
    cout << holder.my_double << endl;


output: 
200044456             //these all 3 are garbage value assign by compiler
-12324924
1.4345345  
_________________________________________________________________
//program to illustrate global declaration concept
#include <iostream>
using namespace std;

struct int_holder
{
    int my_int1;
    int my_int2;
    double my_double;
};


int_holder holder;           

int main()

    cout << holder.my_int1 << endl;
    cout << holder.my_int2 << endl;
    cout << holder.my_double << endl;
 


output: 
0                    //value 0 is assign by compiler because declaration is global
0
0 
----------------------------------------------------------------------------------------------

 //More example to understand concept of Global variable
#include <iostream>
using namespace std;

int example(int x)
{
    x = x+3;
    return x;
}

int main()
{
    int x = 5;
    cout << example(x) << "\t" << x;
}



#include <iostream>
using namespace std;

 int x = 6;   //this global variable now available to every function

int example()
{
    x = x+3;
    return x;
}

int main()
{
    cout << example() << "\t" << x;

 

No comments:

Post a Comment