Passing and processing functions' arguments demonstrating the local and global variable C++ program example

 

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: none

To do: Passing and processing functions' arguments demonstrating the local and global variable C++ program example

To show: How the local and global variable scopes (visibility) implemented in C++ programming

 

// the local, global variables and a function

#include <iostream>

 

// function prototype

void myFunction();

 

// global scope variables

int x = 5, y = 7;

 

int main(void)

{

std::cout<<"x = 5, y = 7, global scope\n";

std::cout<<"\nx within main: "<<x<<"\n";

std::cout<<"y within main: "<<y<<"\n\n";

std::cout<<"Then function call....\n";

 

// function call

myFunction();

 

std::cout<< "Back from myFunction...\n\n";

std::cout<< "x within main again: "<<x<<"\n";

std::cout<< "y within main again: "<<y<<"\n\n";

 

return 0;

}

 

void myFunction()

{

// local scope variable

int y = 10;

 

std::cout<<"Notice the same variable name, y as in main(void)..."<<"\n";

std::cout<<"\ny = 10, local scope\n"<<"\n";

std::cout<<"x within myFunction: "<<x<<"\n";

std::cout<<"y within myFunction: "<<y<<"\n\n";

}

 

Output example:

 

x = 5, y = 7, global scope

x within main: 5

y within main: 7

Then function call....

Notice the same variable name, y as in main(void)...

y = 10, local scope

x within myFunction: 5

y within myFunction: 10

Back from myFunction...

x within main again: 5

y within main again: 7

Press any key to continue . . .

 

 

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