Demonstrating the variables scope (local) within the function block in 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: To demonstrate the variables scope within the function block in C++ program example

To show: How to use the C++ variables scope within the function block

 

// demonstrate the variables scope within a block

#include <iostream>

using namespace std;

 

// function prototype

void myFunc();

 

int main(void)

{

int x = 5;

 

cout<<"\nIn main x is: "<<x;

 

// function call

myFunc();

cout<<"\nBack in main, x is: "<<x<<endl;

 

return 0;

}

 

void myFunc()

{

// local scope variable

int x = 8;

 

cout<<"\nWithin myFunc, local x: "<<x<<endl;

{

cout<<"\nWithin block in myFunc, x is: "<<x;

// another local variable, within block

int x = 9;

cout<<"\nVery local x: "<<x;

}

cout<<"\nOut of block, in myFunc, x: "<<x<<endl;

}

 

Output example:

 

In main x is: 5

Within myFunc, local x: 8

Within block in myFunc, x is: 8

Very local x: 9

Out of block, in myFunc, x: 8

Back in main, x is: 5

Press any key to continue . . .

 

 

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