Hello, I was just looking up the threads and I must say I saw a lot of codes with "std::string", "std::cout", etc... I just wanna ask, wouldn't it be better if you just wrote "using namespace std" instead ? I am doing it all the time, but if it's wrong please tell me so I'd stop :)

Recommended Answers

All 15 Replies

using namespace std;
is correct. That allows you to avoid typing std all the time in your code.

This is a good explaination. Whether to use using namespace std; or not to use it is more of a personal preference than anything else. There is no right or wrong way to do it.

Its your choise if you want to include namespaces, but they are there for a reason, mainly for structuring your code and avoiding name confliction. Take this example:

#include <iostream>

namespace A {
   int var = 10;
};

namespace B {
   int var = 20;
};

using namespace A;
using namespace B;

int main() {
   std::cout << var; // Which one are we talking about ??
   std::cout << A::var; // Displays  10
   std::cout << B::var; // Displays  20
   return 0;
}

Hope this helps.

yeah it's better to include it especially if you have little code
but sometimes you want to just do std::cout or std::endl to make to code more clear

williamhemswort:
A and B are not namespaces. They are c++ classes. You can not give a class the same name as a namespace. And lines 4 and 8 of you code is wrong.

I know ^.^ I changed it as fast as I could, way before you posted.

I know ^.^ I changed it as fast as I could, way before you posted.

where did no change it? Looks the same to me.

include <iostream>

namespace A {
   int var = 10; <<< error here
};

namespace B {
   int var = 20; <<< error here
};

using namespace A; <<< error here
using namespace B; <<< error here
<snip>

It's not only a matter of personal preferences.

I have seen codes where using namespaces std provokes names conflict errors storm. Have you noticed that a code with explicit namespace prefixes is not depended of that "personal preferences" of its (future, unknown) users? It's especially concern of this (and similar) forum snippets (particularly in answers). Explicit std:: prefix used in your header files (in template definitions especially) guarantee an independence of includes and using directives arrangement in cpp files.

The more reusing potential of the code, the more an importance of the full name qualifications without using namespace directives at all (not only for std namespace).

In many cases using-declaration (not using-directive) is enough. For example:

using std::cout;
using std::ostream;
using std::ios;
using std::string;

Consider a typical case in a serious (not homework;)) project. You need (must?) use third-party libraries. Do you want to open all its namespaces in any point your own code? Do you want to rename your own conflicted names after that or to get a very strange results when foreign entities were linked to your code in unexpected manner? But namespace std is the great universe with thousands of names...

So using namespace std is not a good or a bad directive. It is. Don't fall into extremities. It's not a matter of a tastes, it's a matter of reasonable choice.

See also:
http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
http://www.codepedia.com/1/CppNamespace

where did no change it? Looks the same to me.

include <iostream>

namespace A {
   int var = 10; <<< error here
};

namespace B {
   int var = 20; <<< error here
};

using namespace A; <<< error here
using namespace B; <<< error here
<snip>

Ehh ?? Those aren't errors.

commented: you are right :) +34

namespaces are generaly used to avoid conflicts that could happen if you have two functions, classes, etc. with a same name...
so if you've got a libraries "libA" and "libB"
and in each of those you have a function named "f" you need a way to know which function you are actually using. so if you have a namespace ( named "namespaceA" for example ) that has a function "f" from the "libA" library... you can define usage of that namespace to avoid conflicts between the two libraries. so by typing "using namespace namespaceA;" there will be no functions (other than user defined..or not?)
with the same name that could conflict with the one you wish to use (one from the "libA" library.) Now using namespaces can screw up your stuff if you're working with client programs, using tons of different libraries that have functions with same names, so sometimes it's good to only use a part of the namespace as arkm said...
i'm not all that good in this so if i missed something or wrote something stupid please tell me!

@williamhemswort
namespaces shouldn't end with a semicolon (though AD didn't point that out so I'm not sure I'm right about that...). I also don't think non const variables can be defined outside a function, though I could be wrong about that as well. Not sure what's wrong with the using statements.

edit: Checked cplusplus.com - right about no semi-colon, wrong about initializing non-consts.

2 gregorynoob:
Yes, you are on the right track; there are no two ways about it ;).

semicolons
A semicolon by itself is considered a null statement, and has no meaning. Modern compilers will typically complain about them unless they explicitly terminate a statement. For example int number_of_lightbulbs_to_change; ; That second semicolon, while probably not an error, is also not useful, so the compiler will complain. It could be an error: if (foo == mane) padme(); ; else hum(); For counter-example for (int n = 0; quux( n ); n++); This last semicolon is in fact a null statement, but it has a purpose: it expresses an empty loop body.

data initializers
Whether or not you can specify an initializer depends on whether or not the file is #included in another.

// foo.hpp
#ifndef FOO_HPP
#define FOO_HPP
namespace foo
  {
  extern const int fooey;
  }
#endif
// foo.cpp
#include "foo.hpp"
namespace foo
  {
  const int fooey = 42;
  }

This is to obey the One Definition Rule.

when to use using
The difference between header files and object source files is important also when using namespaces. In a header file, you should never (and yes, this is one of those rules), never add stuff to the global namespace. It is not your perogative to decide what the person using your library permits in his namespaces. Example:

// bar.hpp
#ifndef BAR_HPP
#define BAR_HPP

#include <iostream>
#include "bazlib.hpp"

using namespace std;  // <-- WRONG! JUST SAY NO!

using baz::buzz;  // <-- WRONG! JUST SAY NO!

#endif

The reason should be obvious: Anyone who #includes "bar.hpp" also dumps everything in the std namespace and baz::buzz into his current namespace --probably without his knowing! By using using statements in #include files, you take away the programmer's choice not to contaminate his namespace with tons of junk, and doing it fairly negates the whole purpose behind namespaces to begin with. Remember, in headers, just say NO.

linking conflicts
Inside object source files (files that compile into object data; that is, .cpp files), there is no reason why you couldn't use using anything you want. That said, there is still a problem that is often overlooked even by vendors that occasionally causes problems. It is this:
Distinct object files may use the same name for their internal data.
So then, what happens when you try to use both libraries in the same project? If you have a smart linker it will complain and refuse to link them. If not, you've got a 50/50 chance of the linker getting it right for any given reference to the named item. This is actually a serious problem in the industry; one that namespaces were designed to obviate.

Even inside your own object source files you should wrap everything in a local namespace.

// console.hpp
#ifndef CONSOLE_HPP
#define CONSOLE_HPP
#include <string>
namespace console
  {
  int pause( const std::string& prompt = std::string() );
  }
#endif
// console.cpp
#include "console.hpp"
namespace console
  {
  using namespace std;
  int pause( const string& prompt )
    {
    ...
    }
  }

Now, whenever you use a name someone else uses, the linker can still distinguish them and everything works fine. In this example, I used "pause", which is the name of at least two distinct standard functions that I know of. By wrapping it in a namespace, I have protected both my own library and the programmer using it from name collisions.

Of course, there is still the possibility that someone has defined a namespace "console" somewhere --but I would think it unlikely that anyone would use two console management libraries in the same application... (and if they do, there is always dynamic linking, I guess). Alas, even namespaces aren't immune to possible grief.

Anyway, I hope this helps.

Oh, one other note about the #include guards. The ones I included above in my examples are actually fairly simple. You should try to use names that you think very unlikely to be used elsewhere. For example, in my own libraries, I use duthomhas as the enclosing namespace, and I also add it to the #include guard:

// cistring.hpp
#ifndef DUTHOMHAS_CISTRING_HPP
#define DUTHOMHAS_CISTRING_HPP

#include <algorithm>
#include <locale>
#include <stdexcept>
#include <string>

namespace duthomhas
  {
  ...
  template <typename CharType> inline
  CharType uppercase(
    CharType c,
    const std::locale& loc = std::locale::locale()
    } {
    ...
    }
  ...
  }

#endif

This all but guarantees that my libraries will not conflict with anyone else's code.

Enjoy!

commented: Good summary +5
commented: Thats a nice big post :) +3
commented: Yes, Really nice:) +1

Ehh ?? Those aren't errors.

Oops! you are right -- I didn't read it close enough.

commented: Hehe, you make me laugh :) +3

@williamhemswort
namespaces shouldn't end with a semicolon (though AD didn't point that out so I'm not sure I'm right about that...). I also don't think non const variables can be defined outside a function, though I could be wrong about that as well. Not sure what's wrong with the using statements.

edit: Checked cplusplus.com - right about no semi-colon, wrong about initializing non-consts.

Pfftt, not the biggest mistake in the world is it :) and I have no compiler where I am
at the moment (coulden't test) so cut me some slack ;)

commented: For posting code with compiling /testing. -3
commented: It has happened to me before too - you're not alone! =) +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.