The variable scope, global, local and external code sample

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Display some integers

To show: The variable scope, global, local and external

 

// Program object.h, the header file

// extern global variable

// external to object.cpp

extern int global1;

 

// ---class declaration part---

class object

{

public:

int objectvar;

public:

object(void);

int set(int);

~object(void);

};

// this header file cannot be compiled or run

 

 

Add another object.cpp file for the implementation part of the previous code.

 

 

// The class implementation file, program object.cpp

#include <iostream>

#include "object.h"

using namespace std;

 

//extern...

int global1 = 30;

int global2 = 40;

 

//-----class implementation part-----

object::object(void)

{

objectvar = 0;

}

int object::set(int newvalue)

{

int local1 = 10;

 

// non extern with same variables name....

global1 = 60;

global2 = 70;

 

// Display the local variable locally...

cout<<"In object.cpp file, local function, local1 variable = "<<local1<<endl;

 

// Display the global variable locally...

cout<<"In object.cpp file, global1 variable = "<<global1<<endl;

cout<<"In object.cpp file, global2 variable = "<<global2<<endl;

return newvalue;

}

object::~object(void)

{

objectvar = 0;

}

 

Then add mainobject.cpp, the main program and run it.

 

// Program mainobject.cpp, here is the main program,

#include <iostream>

#include "object.h"

using namespace std;

 

// Variables declared here also are global

void main(void)

{

object FirstObject;

// external to object.cpp

extern int global2;

// local to this main() function...

int local2 = 20;

cout<<"In object.h, global1 is object.cpp external variable = "<<global1<<endl;

cout<<"In mainobject.cpp, global2 is object.cpp external variable = "<<global2<<endl;

cout<<"In mainobject.cpp, object value = "<<FirstObject.set(50)<<"\n";

cout<<"In mainobject.cpp, local function, local2 variable = "<<local2<<endl;

}

 

Output example:

 

In object.h, global1 is object.cpp external variable = 30

In mainobject.cpp, global2 is object.cpp external variable =

40

In object.cpp file, local function, local1 variable = 10

In object.cpp file, global1 variable = 60

In object.cpp file, global2 variable = 70

In mainobject.cpp, object value = 50

In mainobject.cpp, local function, local2 variable = 20

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index