Thread: What is?

  1. #1
    DJ who loves Goa Trance!!
    Join Date
    Sep 2004
    Posts
    7

    What is?

    What does Usingnamespace STD mean? And how do you implement it in your code?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    The latest C++ standard places everything in the standard library in a namespace called std. A namespace is basically a separate list of names so that the standard names don't get mixed up with names that you declare if they happen to be the same. This is a good thing, but it does make it necessary to tell the compiler which name you're talking about when you use it. This is done by qualifying a name with the namespace:
    Code:
    <namespace>::<name>
    So to use cout you would say std::cout. Because many programmers hate doing this for every name, C++ allows you to say "I'm going to use names from this namespace and I don't want to qualify them and I don't care about name clashes". That's where the using directive comes in. When you say
    Code:
    using namespace <namespace>;
    You implicitly qualify names in that namespace. So:
    Code:
    using namespace std;
    Means you no longer have to say std::cout, you can now just say cout and the compiler will know what you mean.
    My best code is written with the delete key.

  3. #3
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    >And how do you implement it in your code?
    You can implement it in several ways. You can put it near the top of your file, outside of any scope, so that the compiler will find standard library names throughout the code in that file.
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout << "Hi Mom!" << endl;
    }
    You can also put inside a certain scope so that within that scope you don't have to specify the namespace every time:
    Code:
    #include <iostream>
    
    int main()
    {
        for (int i = 0; i < 10; ++i)
        {
            using namespace std;
            cout << i << " ";
        }
    
        std::cout << "Hi Mom!" << std::endl;
    }
    And finally, you could do something similar and add using directives for only certain members of the std namespace (or any other namespace). For example:

    using std::cout;
    using std::cin;

    Those can be placed globally or locally like the other using namespace directive above.

    Of course some people (like me) prefer never to use a using directive for the std namespace, and just type std:: before each standard library name.

Popular pages Recent additions subscribe to a feed