Search

4.3c — Using statements

If you’re using the standard library a lot, typing “std::” before everything you use from the standard library can become repetitive. C++ provides some alternatives to simplify things, called “using statements”.

The using declaration

One way to simplify things is to utilize a using declaration statement.

Here’s our Hello world program again, with a using declaration on line 5:

The using declaration “using std::cout;” tells the compiler that we’re going to be using the object “cout” from the std namespace. So whenever it sees “cout”, it will assume that we mean “std::cout”. If there’s a naming conflict between std::cout and some other use of cout, std::cout will be preferred. Therefore on line 6, we can type “cout” instead of “std::cout”.

This doesn’t save much effort in this trivial example, but if you are using cout a lot inside of a function, a using declaration can make your code more readable. Note that you will need a separate using declaration for each name you use (e.g. one for std::cout, one for std::cin, and one for std::endl).

Although this method is less explicit than using the “std::” prefix, it’s generally considered safe and acceptable.

The using directive

Another way to simplify things is to use a using directive statement. Here’s our Hello world program again, with a using directive on line 5:

The using directive “using namespace std;” tells the compiler that we want to use everything in the std namespace, so if the compiler finds a name it doesn’t recognize, it will check the std namespace. Consequently, when the compiler encounters “cout” (which it won’t recognize), it’ll look in the std namespace and find it there. If there’s a naming conflict between std::cout and some other use of cout, the compiler will flag it as an error (rather than preferring one instance over the other).

There’s open debate about whether this solution is good practice or not. Because using directives pull in all of the names in a namespace, the chance for a naming collisions goes up significantly (but is still relatively small).

Suggestion: We recommend you avoid “using directives” entirely.

An ambiguity example with using directives

For illustrative purposes, let’s take a look at an example where a using directive causes ambiguity:

In the above example, the compiler is unable to determine whether we meant std::cout or the cout function we’ve defined. In this case, it will fail to compile with an “ambiguous symbol” error. Although this example is trivial, if we had explicitly prefixed std::cout like this:

or used a using declaration instead of a using directive:

then our program wouldn’t have any issues in the first place.

Many people avoid “using directives” altogether for this reason. Others find them acceptable so long as they are used only within individual functions (which limits the places where naming collisions can occur to just those functions).

Limiting the scope of using declarations and directives

If a using declaration or directive is used within a block, the using statement applies only within that block (it follows normal scoping rules). This is a good thing, as it reduces the chances for naming collisions to occur just within that block. However, many new programmers put using directives into the global scope. This pulls all of the names from the namespace directly into the global scope, greatly increasing the chance for naming collisions to occur. This is considered bad practice.

Rule: Avoid “using” statements outside of a function.

Cancelling or replacing a using statement

Once a using statement has been declared, there’s no way to cancel or replace it with a different using statement within the scope in which it was declared.

The best you can do is intentionally limit the scope of the using statement from the outset using the block scoping rules.

Of course, all of this headache can be avoided by explicitly using the scope qualifier operator (::) in the first place.

4.4 -- Implicit type conversion (coercion)
Index
4.3b -- Namespaces

43 comments to 4.3c — Using statements

  • josiah jackson

    instead of:

    #include

    int main()
    {
    std::cout << "Hi!" << std::endl;
    std::cout << "My name is Alex." << std::endl;
    }
    _________________________________________________________________________________________________

    couldn't i just use (using namespace std;) in the beginning

    #include
    using namespace std;

    int main()
    {
    cout << "Hi!" << std::endl;
    cout << "My name is Alex." << std::endl;
    }

    • N

      In this case, you may write ‘endl’ instead of ‘std::endl’ :

      using namespace std;

      int main()
      {
          cout << "Hi!" << endl;
          cout << "My name is Alex." << endl;
      }

      • Alex

        Generally, using directives should not be used outside of function bodies. Instead of:

        It’s much better to do this:

        • Odgarig

          What if after using namespace std; I needed to use another objects not from the standard library, but from the other library I created ? THANK YOU.

          • Alex

            It’s no problem.

            If the objects in your own library are not in a namespace, just call them directly (e.g. doSomething()).

            If the objects in your own library are in a namespace, either call them directly (e.g. myNamespace::doSomething()) or use a using statement for that library (eg. using namespace myNamespace) and then call them directly (e.g. doSomething()).

            As long as the names of the objects in your library are different than those in the standard library, you won’t have any problems.

            And even if you do encounter a naming collision, there are ways of working around it. For example, you can remove the using statements and use explicit qualifiers (e.g. std:: or myNamespace::).

  • Catreece

    Thanksies muchly for the site and tutorials, really handy and much better than the last time I tried to learn C++ a few years ago from a textbook riddled with several typos per page (yeah, fun debugging when you don't even know what the syntax is supposed to look like -_-; )  so this is a huge improvement.

    Decided to take the basic concept a step further with the std::cin statement test:

    int main()
    {
        // set cout to std::cout because I'm lazy :: also test that this statement works properly
        using std::cout;

        // test to make sure cin works the way cout does
        using std::cin;

        /* Also using only individual commands :: I don't trust automating more than absolutely neccessary.
        * Computers are stupid, don't entrust them with anything that may involve making a decision.
        * Since "using namespace std;" requires the computer to make a decision if two commands overlap,
        * I'm simply not willing to entrust it with a decision because, with my luck, it'll make the wrong call. */

        // Also, the above is a test of enclosed comments across multiple lines.

        // set X and Y variables first, prefer to set early before messing with anything else

        // defaults X so it doesn't break when called
        int x = 0;

        // defaults Y so it doesn't break when called
        int y = 0;

        // ask user for a number,
        cout << "Enter a number:";
        
        // read number from console and store it in x
        cin >> x;
        
        // ask user for a second number
        cout << "Enter a second number:";
        
        // User inputs Y value :: test for second variable and order
        cin >> y;

        // adds totals and displays X+Y :: test for expression
        cout << "You entered a combined total of " << x+y << std::endl;
        return 0;
    }

    I like to test things like this by running several previous things I've learned together to make sure they actually work the way I think they do. In this case, I discovered that the space at the end of "Enter a number: " in the original example is unnecessary in some cases; you can't see it anyway, since it's a command prompt and the only thing different would be a space between the : and your inputted integer. The space makes it a little prettier, but doesn't stand out as especially needed.

    The second thing was actually the first chronologically discovered; the realization that when I put in:

        std::cout << "You entered a combined total of" << x+y << std::endl;

    …it printed off "You entered a combined total ofX"

    This meant I had to go searching for where the space was coming from, which turned out to be included within the end of the quotations. This also made me curious, since it means spaces are preserved in quotes, so does it minimize it to one space or does it count all spaces?

    A simple test of adding 3 spaces to the end of the quotations so it'd be obvious verifies that, yes, C++ does in fact preserve all spaces entered within quotations.

    Combined with checking the printed data, and noting it has a monospaced font, this means it can be used to print off ASCII art. =P

    Anyway, mostly irrelevant, but it did prove that the code works (mostly) the way I thought it did, and I was able to learn some neat things by testing some variations thereof.

    For any newbies reading, I'd generally recommend running the presented text first (write it out manually instead of copy/paste, helps you to remember the commands via repetition), and then do something a little different to test how it works in practice under new conditions. It helps to make sure you understand what's happening and why it's working, and if something breaks during the test, it means you did something wrong in an enclosed environment where you can't break too much.

    Better to screw up while learning in a relatively safe area than screw up later on when getting paid and your boss gets pissy when you break it and spend an hour debugging something you could've learned early on. Learning involves making mistakes; use your learning time to get all the mistakes out of the way by feeling out what works and what doesn't before it matters. =3

    Also, while I overdid it (many times over) with the comments, in past experience I've learned spending 15 minutes writing out clear explanations for why you did something will save you hours of work later on when it invariably breaks and you can't recall what you were thinking at the time you wrote it. It's even more useful if someone else has to read your code or work because they may not come to the same conclusions you did, such as "using std" instead of "using namespace". Any time there's a judgement call, give a clear explanation, it'll save headaches in the long run, even if it feels like a waste of time now.

    • Alex

      Great use of experimentation to aid your learning process. I’d second the advice for readers to play with the examples and extend/alter them as a way to learn.

    • _aleph_

      I totally agree with “write it out manually instead of copy/paste, helps you to remember the commands via repetition.”  What seems a waste of time now is, in reality, a tremendous blessing when you are writing code and have no source for copy/paste.

      Also, concerning commenting, there was I think a moderator (maybe a frequent poster) on the AutoIt forum who had a signature that may embody the need for commenting.  I don’t remember exactly, but it was something like this:  “I was looking at some code and wondering what drugs this guy was on, then I remembered that I wrote the code.”  Of course it was funny, but I believe it could have been a lack of appropriate commenting.  Another option was that he might have written inelegant code in the first place.  But the lesson about commenting is there. The coder didn’t know why the code was written in the way it was.

      _aleph_

  • Alex D.

    Hello,

    When we use "using namespace std" we tell compiler to look into a whole class for definitions of objects like "cout"
    other way is, explicelty define the desired object like,
    using std::cout;
    using std::cin;
    using std::endl;

    My doubt is, if we are dealing with a very large file, will that going to affect the execution time?
    I mean what will be the optimised way of using it?

    second doubt is silly…well how do people paste the snippet of their code when they comment here?

    • Alex

      All identifier resolution happens at compile/link time, so there’s no runtime performance penalty for using using statements (it could make your compilation take longer though).

  • Johnny V

    Hey there,

    Just curious. In this code on the last example you gave:

    #include <iostream>

    int main()
    {
       using namespace std; // this using directive tells the compiler that we’re using everything in the std namespace!
       cout << "Hello world!"; // so no std:: prefix is needed here!
       return 0;
    }

    you didnt put endl after the hello world.. if thats the last bit of code that your going to use  before the return do you need to put it still?

    • Alex

      If it’s the last line of code, it doesn’t matter whether you use std::endl or not. I omitted it from the example just to keep things simpler.

  • Dustyn

    When using the Using Declaration for cout as noted above under "The Using Declaration", is it correct that since it is within the main() function that it will only work within that function? Say if I went to another function, would I have to enter in

    again for it to work within that function?

    Just trying to clear some things up for myself as i’m taking notes as I go through these Chapters/Sections.

    Thanks!

  • Chance

    Just to be clear, how do prefixes, directives, and declarations interact if used together? Is there some sort of order of magnitude, do they cause errors, or does something else happen? For instance, if I write a directive that calls on a library with a cout function other than std, but also write a declaration of using std::cout;, what will the compiler do? And what about other scenarios, like directive vs. prefix, or declaration vs. prefix?

  • JackTheBeanstalk

    I’m not sure I understand why using

    would be preferable to using

    in that last example? Surely both would equally cause a name collision if you have a function called cout?

    I understand why

    would avoid the collision, but why would using a declaration statement instead of a directive statement?

    • Alex

      Good question. As you’ve correctly noted, “using std::cout” is no better than “using namespace std” for avoiding naming collisions with the specific identifier “cout”.

      However, consider the case where you had written a function named “cin”. In this case, “using std::cout” wouldn’t cause a naming collision, but “using namespace std” would. In other words “using std::cout” only has the potential to cause a naming collision with the identifier “cout”, whereas “using namespace std” has the potential to cause a naming collision with _every_ identifier in the std namespace (and there are a lot!).

  • Ajit Nain

    In the case above everything inside std namespace is brought into the scope of main function so compiler is not able to resolve between user defined cout() function and namespace cout object.

    but in the case below using std::cout we still brought cout object to the scope of main so how compiler resolve between these two now as function cout() is still acessible in main;

    • Alex

      In the case where we do “using namespace std”, we import all of the names, but we haven’t told the compiler anything about how to prioritize conflicting names.
      In the case where we do “using std::cout”, we’re explicitly telling the compiler “when you see cout(), we mean std::cout”, so it knows how to resolve this, even when it sees a conflict.

  • silvia

    Thanks for the very clear and complete tutorial! A question about namespaces. What if I still want to have a function called cout in my code and call it in the main function, where I’m using std namespace declaration? Should I declare a namespace?

    • Alex

      You can either put your version of cout in a separate namespace (and then access it via namespace::cout), or leave it in the global namespace and access it via ::cout (nothing before the ::, which indicates the global namespace).

  • swapnil

    #include <iostream>
    int cout()
    {
        return 5;
    }
    int main ()
    {
        using namespace std;
        cout << "Hello world";
        return 0;
    }
    The abve program executed well without any error. It displayed Hello world. Pls let me why didnt it gave error.

    • Alex

      Unsure. Perhaps your compiler was able to intelligently resolve the ambiguity. Visual Studio 2015 gives an ambiguous symbol (naming conflict) between our int cout(void) function and std::ostream std::cout.

  • DuoDynamo

    Hello there!

    In the collision example you provided, I didn’t quite understand why a using declaration prevents collisions while a using directive does not. Isn’t cout trying to use the std namespace WHILE declared as a variable either way?

    Thanks in advance, and thank you VERY much for this tutorial. 🙂

    • Alex

      A using declaration says “treat all instances of name X as namespace::X” (which implies a priority in the case of conflict). A using directive says “import all of these names from the namespace”, but doesn’t tell you which to prefer if a conflict occurs.

  • Ankit

    In the collision example you    used the directive statement within the main function but then also naming collision happened.Why?

    • Alex

      Using directives don’t provide any priority for the compiler to pick which version of the function it should. So in this case, it’s not sure whether it should use our version of cout() or std::cout().

      That’s one reason why using declarations are better: if a naming collision occurs, it’ll use the one specified in the using declaration.

      • Ankit

        But why    is the compiler unable to know the difference b/w a function we defined and a keyword.We always write a function along with these set of brackets ().And in the collision example inside the main function no such () brackets were used.so wasn’t that obvious that we were actually talking about the "cout" keyword their.

        • Alex

          That’s a good question. I’m not sure why the compiler can’t disambiguate that one version of cout is a function and the other is an object of type std::ostream.

  • NoobtoProgramming

    Hi Alex,

    First, I really want to thank you for creating such a helpful website. Your explanation is very clear to follow.

    Just one quick question. So I changed the cout operation a bit as below.

    #include <iostream>

    int cout(){
        return 10;
    }

    int main(){
        using std::cout;
        cout << cout();

        return 0;
    }

    This produces an error message: type ‘ostream’ (aka ‘basic_ostream’) does not provide a call operator

    But if I get rid of using std::cout & put in std::cout << cout();, then
    it works.

    Is this a dead-end, which forces me to put in the std::cout << cout();?

    Any work around this where I can still use the namespace directive or std::cout declaration?

    • Alex

      Yes, your example is producing a naming conflict, because the compiler doesn’t know whether you mean your cout() or std::cout(). There’s no way to fix this using a using directive (that’s what’s causing the issue in the first place).

      While you found one way to resolve the issue (explicit use of std::), another way would be to give your function a different name to avoid the naming conflict altogether.

  • Ari Kim

    Do you know if there would be any possible way to sum this up, or simplify it at least? It just seems really long and irritating.

    • Alex

      There’s no way to simplify the general logic, but you could condense this a bit by not commenting the vanity spacing lines and combining those with the previous print statements

      e.g:

  • Erad

    Hi Alex,

    I have a question about how the "using" statement (line 5) is used in the code below. This is a little different from what I am used to or what your literature here explains. I am mostly confused about the equality(=) sign used in the using statement. Please explain.

    Moreover, why does the statement in line 17 have nothing preceding the scope resolution operator :: ? What is going on here?

    • Alex

      “using” is one of the C++ keywords that has a lot of different meanings depending on context. This form of using is called a type alias, and it is used to give a type an easier to remember/use name (in this case, StringPtr now means std::shared_ptr). I talk about type aliases in lesson 4.6.

      The scope resolution with nothing preceding it is used to indicate that the object being resolved lives in the global scope. In this case, the :: is extraneous because there’s no other definitions of print_count to conflict with. However, if main() had an identifier named print_count (a variable or a type), then print_count would select that name instead of the one in the global scope (the locally defined print_count would hide/shadow the global one). In that case, the :: could be used to say, “no, I mean the print_count that lives in the global scope, not the locally defined one”. I talk about shadowing in lesson 4.1a and :: as a prefix in lesson 4.3b.

  • Zhengxiu

    Hi, Alex
    I understand that the prefixes are always explicit, so they are always safe. Now I want to know if there is some sort of order of magnitude between the using directive and using declaration.
    For example, if I build a namespace called "mynamespace" with a cout function in it(I’m new to C++ and don’t know how to do it yet). Then I put this

    int cout()
    {
      …
    }
    int main()
    {
      using namespace mynamespace;
      using std::cout;
      cout ….
    }
    What will actually happend?
    Also is there a explicit qualifier for the function(in the above example the "int cout()" function) that I created?
    Thank You!

    • Alex

      The more specific using declaration (using std::cout) takes precedence over a using directive (using mynamespace).
      Assuming your cout() function was inside namespace mynamespace, the qualifier would be mynamespace::cout.

      I talk more about namespaces and how to create your own in chapter 4.

  • imah

    if we avoid use cout as function, will it reduce naming collision?

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter