An example of using the same variable name in different scopes source code

This snippet submitted by Ali Nawkhas Murad on 2012-01-03. It has been viewed 8285 times.
Rating of 6.1 with 77 votes

// An example of using the same variable declarations in different scopes in C++ without conflicts

#include <iostream>

using std::cout;
using std::endl;

class abc  //Class declaration statement, you can use struct, and union also.
{
    public:
    int x;  //Variable declaration within class.
    abc():x(10){}  //Constructor to intialize data members.
};

namespace def  //Namespace declaration statement.
{
    int x = 20;//Variable declaration within def space.
}

int getx()  //Function return its local variable.
{
    int x = 30;   //Variable declaration within function space.
    return x;
}

int x = 40;   //Global space variable declaration.

int main()
{
    int x = 50;//Local space variable declaration within main function.
    abc a;

    cout << "Scope within class abc:  x = " << a.x
         << "\nScope within namespace def:  x = " << def::x
         << "\nScope within function getx:  x = " << getx()
         << "\nScope within global scope :  x = " << ::x
         << "\nScope within local main function:  x = " << x;

         {
             int x = 60;  //Local scope variable declaration within segment of code
             cout << "\nScope within local code block:  x = " << x;
         }
         cout<<endl<<endl;//Send two new line to the screen

    return 0;
}

/*Program Output:
Scope within class abc:  x = 10
Scope within namespace def:  x = 20
Scope within function getx:  x = 30
Scope within global scope :  x = 40
Scope within local main function:  x = 50
Scope within local code block:  x = 60
*/

 
 
 
 
 
 




More C and C++ source code snippets

Add a snippet!