Saturday, September 19, 2009

The using and namespace keyword in C++


The using and namespace keyword in C++

Using the using keyword

You may feel it is inconvenient to write std:: in front of cout and endl every time. There is two solution provided by ANSI standard. It is done by use of the keyword using. The first solution is by calling specific standard library explicitly. For example, if we want to use cout and endl which is a part of standard library, we have to call standard library for cout and endl before using them. The following program demonstrates the first solution.

A C++ Program example that calls specific standard library.


#include <iostream>

int main ()
{

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

    cout << "Lets have a look on cout !!" << endl;
    cout << "The number 99 : " << 99 << endl;
    cout << "The sum of of 9 + 8 : "<< 9 + 8 << endl;
    cout << "The division of 7 / 18: "<< float (7 / 18) << endl;
    cout << "The multiplication of 6000 & 6000 : "
            << double (6000 * 6000) << endl;
    cout << "Replace Mohammed Homam with your name ..." << endl;
    cout << "Mohammed Homam is a C++ programmer" << endl;

    return 0;
}


Using the namespace keyword

The second solution to avoid the inconvenience of writing std:: in front of cout and endl is by calling the entire standard namespace. It means that you don't have to call any standard library function explicitly. All standard library functions will be called by single statement. The following program demonstrates the second solution.

A C++ Program example that calls entire standard library.


#include <iostream>

int main()
{

    using namespace std;

    cout << "Lets have a look on cout !!" << endl;
    cout << "The number 99 : " << 99 << endl;
    cout << "The sum of of 9 + 8 : " << 9 + 8 << endl;
    cout << "The division of 7 / 18: "<< float (7 / 18) << endl;
    cout << "The multiplication of 6000 & 6000 : "
            << double (6000 * 6000) << endl;
    cout << "Replace Mohammed Homam with your name..." << endl;
    cout << "Mohammed Homam is a C++ programmer" << endl;

    return 0;
}

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Want to learn more? View List Of All Chapters

1 comment:

  1. Nobody can reject the info you have given in the blogs, this is actually a great work.
    tutorial on c++

    ReplyDelete