Saturday, 10 November 2012

Program illustrating Namespaces in C++

//The following programs illustrates namespaces in C++
//Compare the syntax of the three Programs you will understand the scope of namespaces in C++
//Program 1 begins here.

#include<iostream>
#include<typeinfo>
using namespace std;
namespace{
    int i=444;
}
namespace ns1
{

int j=555;
namespace ns2
{
    int k=666;
}
}

int main()
{
    cout<<"\ni is: "<<i;
    cout<<"\nj is: "<<ns1::j;
    cout<<"\nk is: "<<ns1::ns2::k;
    return 0;
}

//Program 2 Begins here.
#include<iostream>
#include<typeinfo>
using namespace std;
namespace{
    int i=444;
}
namespace ns1
{

int j=555;
namespace ns2
{
    int k=666;
}
}
using namespace ns1;
using namespace ns1::ns2;
int main()
{
    cout<<"\ni is: "<<i;
    cout<<"\nj is: "<<j;
    cout<<"\nk is: "<<k;
    return 0;
}

//Program3 begins here.
#include<iostream>
#include<typeinfo>
using namespace std;
namespace{
    int i=444;
}
namespace ns1
{

int j=555;
namespace ns2
{
    int k=666;
}
}

using namespace ns1::ns2;
int main()
{
    cout<<"\ni is: "<<i;
    cout<<"\nj is: "<<ns1::j;
    cout<<"\nk is: "<<k;
    return 0;
}


Click below to download the C++ Programs.


No comments:

Post a Comment