Computer Programming web Web programming Tips



Variable scope

By Sergey Skudaev


The following C++ code example includes declaration of message variable inside Greeting class, inside PrintMessage method of the class and inside the main function. In each place message variable is assigned different values. Inside class message="Hello World\n", Inside PrintMessage function message="How are you?" and inside main function message="Hi There". When you execute the program, command prompt window display: "How are you?" because class level variable is not visible inside the PrintMessage function in scope of the local variable with the same name. A variable inside the main function and outside the class is most global and therefore it is not visible as well.

If you comment the line message="How are you?", compile and execute the code again command prompt display "Hello World" Now class level variable becomes visible. The variable message inside the main function and outside the class is more global than class variable and is not visible inside the class in scope of class variable with the same name.It is visible outside the class. If you copy the line



     cout<<message<<endl;

inside the main function like that:

#include<iostream>

using namespace std;

int main(int argc, char* argv[])
{
	char* message="Hi There!";

Greeting gr;
gr.PrintMessage();

 

     cout<<message<<endl;

int hold = 1; cin >> hold; return 0; }

Compile and execute the code. Command prompt displays:

Hello World

Hi There!

"Hello World" is output of gr.PrintMessage() line and "Hi there" is ouput of cout<<message<<endl; line

If you comment line message="Hello World\n"; inside the class constructor compile the code and try to execute it, program crashed because no value assigned to pointer char* message inside the class

There is the complete code:


#include<iostream>

using namespace std;

class Greeting
{

public:

void PrintMessage();

Greeting();


private:
char* message;
};


Greeting::Greeting()
{
message = "Hello World\n";
}


void Greeting::PrintMessage()
{
	     char* message="How are you?";

        cout<<message<<endl;
}


int main(int argc, char* argv[])
{
	char* message="Hi There!";

Greeting gr;
gr.PrintMessage();

    int hold = 1;
    cin >> hold;

return 0;
}<



 << PART I - Data Type
 << PART II - Pointers and Functions 

My eBooks on Amazon.com

US    UK    BR    CA
US   UK   BR   CA
US    UK    BR    CA