6.12 — 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.

Using declarations

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

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

The using declaration of 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 many times 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, etc…).

Although this method is less explicit than using the std:: prefix, it’s generally considered safe and acceptable (when used inside a function).

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).

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 the x in main refers to a::x or b::x. In this case, it will fail to compile with an “ambiguous symbol” error. We could resolve this by removing one of the using statements, or using an explicit a:: or b:: prefix with variable x.

Here’s another more subtle example:

In the above example, the compiler is unable to determine whether our use of cout means std::cout or the cout function we’ve defined, and again 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.

Limiting the scope of using declarations and directives

If a using declaration or using directive is used within a block, the using statement applies only within that block (it follows normal block 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 (see lesson 2.9 -- Naming collisions and an introduction to namespaces for more information on this).

Best practice

Although many textbooks and tutorials use them liberally, avoid using directives altogether. Using declarations are okay to use inside blocks, where their impact is limited, but not in the global scope.

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 resolution operator (::) in the first place.

6.13 -- Typedefs and type aliases
6.11 -- Scope, duration, and linkage summary

115 comments to 6.12 — Using statements

  • Aadithya MD

    I don't get any conflict for the following code:


    "If the compiler finds a name it doesn’t recognize, it will check the std namespace."
    In this example cin is recognised as local variable so it overrides std::cin.

    gcc version 7.3.0

    • Alex

      In this case, that's because local variable cin is shadowing std::cin, which is globally scoped. Local variables take precedence over identically named global variables when called from within the function where the local variable is defined.

  • Frederico Machado


    As I understood when you use the 'using' statement for an entire namespace, you call it a 'using' directive.
    My understanding was that directives had the # prefix and were resolved by the pre-compiler. Is the 'using' directive resolved by the pre-compiler, or does directive have multiple meanings like 'static'?

    • Alex

      Good point. The directives that start with # are called preprocessor directives, and those are the ones that are processed by the preprocessor.

      Using-directives are not preprocessor directives, and are processed by the compiler, not the preprocessor.

  • Hamed O.Khaled

    Hi Alex!
    the out put of this example was confusing to me until I tried it on my own .. can u provide section for such situations ?

    also what is the mechanism that c++ use when multiple namespaces are in use with each has it's unique identifiers ?

    • Alex

      I've updated the lesson to include a similar example.

      I'm not sure what you mean with your last question. There's no problem having multiple namespaces in use (even if they have identifiers with the same names), so long as the compiler can always be sure about which identifiers we mean.

      • Hamed O.Khaled

        If we have multiple namespaces with same identifiers , whenever we try to use an identifier that has duplicate name we should specify in which namespace it should look for namespace::identifier other wise it will complain.
        what I'm asking is in this code:-

        how it finds the proper namespace for identifier y ? is C++ brute-force for all namespaces in use ??

        • Alex

          Because you've used "using namespace hamed" and "using namespace omar", when you use y, it will check both namespaces. If it finds y in either, it will use it. If it finds y in neither or both, it will give an error.

  • Sooi Shanghei

    I don't know if others find this misleading but I think title could be ~~ "Using" statements ~~. To someone unfamiliar with the topic, it might sound to them like this lesson called ~~Using statements~~ is teaching you how to, literally, use statements! (Which was already covered in 1.1 - Structure of a program)

  • alljust4forfun

    I would be really appreciate if you could clarify what happens if we have 2 subsequent using statements like in this example:

    from which namespace will be used??

    • Alex

      If somefunc is defined in both MyNS1 and MyNS2, then this will be an ambiguous identifier and the compiler will complain that it doesn't know how to resolve the situation.

  • Dani

    Hi, Alex. I have a question regarding why is better practice the "using declaration" rather than the "using directive".

    I get that importing the whole namespace is probably not necessary in most cases and so is better to avoid possible name conflicts.

    But assuming the name conflict happens, isn't it desirable to have the compiler tell you it doesn't know what to do, rather than just make an assumption that maybe the programmer forgot, and behave unexpected?

    • Alex

      Using declarations make your intention clear: If a naming conflict occurs, the compiler should resolve it in a particular way. Using directives don't make your intention clear, so the compiler has to ask.

      If you tell the compiler you want an identifier to be resolved in a particular way, you'd better be certain. :)

  • Hema

    Does "using std::cout" have block scope?

  • Hema

    Wouldn't just typing "cout" refer to standard library?

  • madilyn

    how come an experienced programmer like you didn't have a chance to create one of those successful applications and make a fortune, if you couldn't do it then maybe i don't have a chance, right Alex?

    • Alex

      There are some crazy assumptions going on here. Let me just say: You have a chance. Whether that chance is big or small depends on a huge number of factors, some of which are under your control (your skills and your preserverence) and some of which are not (luck).

  • Muhammad Hassan Javed

    Never understood namespaces or the purpose of namespaces before. learncpp saves my life. thanks for your efforts sir Alex. I also want to be a programmer who will not only program but also teach others. Thanks a lot, a great inspiration for me.

    • Alex

      You're welcome. The best way to ensure you really understand something is to teach others. You'll very quickly find out where the gaps in your knowledge are. :)

  • justin

    In the case of using declarations I use "using std::cout" and I wanted to use a different cout in the global namespace, can I just prefix it like this "::cout"" without any problems?

    • Alex

      It depends. If your using namespace std is inside the function, then using the global namespace prefix (::) should resolve to your user-defined function. If your using namespace std is in the global space (outside of a function) then that won't work.

  • Curiosity

    you said that,
    If a using declaration or directive is used within a block, the using statement applies only within that block (it follows normal scoping rules).

    then why does this produce an error ?

    • Alex

      When you do a "using namespace std;" inside of main, everything inside namespace std is now accessible without the std:: qualifier while inside main.

      That means inside of main, there's now a conflict between our user-defined cout and std::cout, because the compiler can't tell which one "cout" refers to.

      • Curiosity

        Uh-Oh ! I dint understand ! Do U Mean  that even if the using namespace std was declared inside of main, i can access everything out of main(), But How? How can it Go Out Of Scope !?

        • Alex

          No. If you do a using statement inside a function, that using statement only applies within the function. Since you did a using namespace std inside of main, then inside of main you don't need the std:: prefix. But you would need it outside of main. The problem here happens because:
          1) There is a function above main() named cout(), and this cout is visible inside of main.
          2) #include iostream is bringing in another declaration for cout. Normally this wouldn't cause a problem because cout would be our function, and std::cout would be the one in iostream, but the using statement tells the compiler that std::cout should be called cout, which conflicts with the function we defined above.

          We would have the same problem if the using statement were used above main(), so that the objects in the standard library could be accessed without the std::prefix anywhere below that point in the file.

          • Curiosity

            Ok. So, you mean that  using statement doesnt apply within main(), so, it didnt see the cout inside of main but as iostream brought in the declaration of std::cout it conflicted with the cout function......

            But, then,
            What is the difference b/w Using Statement declared globally and statement declared inside a function ?

            • Alex

              > If you do a using statement inside a function, that using statement only applies within the function. Since you did a using namespace std inside of main, then inside of main you don’t need the std:: prefix.

              A using statement inside the function applies the effect of the using statement for the rest of that function only. A using statement outside the function applies to the rest of the file.

              • Curiosity

                Thats what i'm asking....if it only applies for within that function so why did it show an error even when the cout() function was declared globally and was outside the scope of main().And, The Cout() Function is even not called.

                And If It is able to see outside of main() then it must be same as "using directive that is declared globally".

                • Alex

                  Remember that in a .cpp file, anything declared is visible until the end of the scope it is declared in. That means if something is declared in a function, it's visible until the end of the function. If something is declared in the global part of the file (outside of a function), it's visible until the end of the file.

                  So when we #include iostream, all of the declarations in iostream are visible and usable for the rest of the file. When we define function cout, that cout is visible and usable for the rest of the file.

                  Inside of main(), there are three things happening:
                  1) The using statement make all of the functionality in namespace std accessible without the std:: prefix. Because the using statement is declared within the function, this is true only until the end of the function.
                  2) Because of the using statement, the std::cout from iostream (now accessible as just cout) and the cout from the function we defined are both visible from within the main() function, thus causing a potenital naming conflict.
                  3) The use of cout in the statement following the using statement cause the compiler to not be able to disambiguate which cout we mean, causing an error.

                  This potential conflict actually happens because we are using cout in the statement following the using statement.

                • Curiosity

                  Ok Man I Understood ! Tell me if i am right .... If we would have declared the cour functiom below main() then it would not have been able to identify cout() and would have used std for cout in main() ( as we all know compiler reads files sequentially )

  • nikos-13

    int main()
        using namespace Foo;

        using namespace Goo;

        return 0;

    So, we can't do this???

  • imah

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

  • 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.

  • 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.

  • 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


  • 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.

  • 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 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.

  • 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.

  • 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.

  • 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).

  • 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.

  • 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!).

  • 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?

  • 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.


  • 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.

  • Alex D.


    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).

  • 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; 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.


    • This is a wonderful approach to learning. I'm sure by now you know that a 'space' is actually a character with an ASCII value...

  • josiah jackson

    instead of:


    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

    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::).

Leave a Comment

Put all code inside code tags: [code]your code here[/code]