4
using namespace std;

So far in my computer science courses, this is all we have been told to do. Not only that, but it's all that we have been allowed to do, otherwise we get penalized on our code. I understand, through looking at code posted online, that you can use ::std or std:: to accomplish the same thing.

My question is generall why? Obviously for the sake of learners and simplicity using the global declaration is simpler, but what are the draw backs? Is it more realistic to expect ::std in a real world application? And I guess to add on to this, what is the logic/concept behind the using declaration? None of this has been explained during my courses, and I'd like to get a better grasp on it.

As a general question: if I haven't been taught this content, vectors, templates, classes, or error handling does it seem like I'm missing a lot of essential C++ functionality?

Thanks in advance!

user3857017
  • 265
  • 4
  • 14
  • 2
    I would suggest a little time reading [this question and its various posted answers](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). An *outstanding* example of a situation where `using namespace std;` innocently sitting in some translation unit had unexpected consequences [can be seen here](http://stackoverflow.com/questions/2712076/how-to-use-an-iterator). It is worth the read. – WhozCraig Oct 11 '14 at 21:31
  • Thanks, I'll check it out! I tried to find some examples beforehand, but a lot of it was like "Yeah it can cause problems *sometimes*." with no proof. – user3857017 Oct 11 '14 at 21:41
  • 1
    The ***indiscriminate*** use of `using namespace ...` is IMHO **bad practice** that can lead to many subtle, hard to find bugs. It circumvents the entire reason namespaces were introduced into the laguage to begin with. That being said there are proper uses for `using namespace ...` when its scope is **restricted** (either by namespace or local scope). Even so the `std` namespace is very large and contains **many** common symbols so I ***always*** avoid `using namespace std`. **Also see:** [The C++ FAQ](http://www.parashift.com/c++-faq/using-namespace-std.html) – Galik Oct 11 '14 at 21:48
  • I see, I wasn't aware (before asking this) that you could use using inside of a function, and assumed it only worked in global space. – user3857017 Oct 11 '14 at 22:01
  • 2
    But I should add, ***do what your CS professor tells you for your class*** but don't accept anything one person tells you as gospel. Learning *best practices* is an ongoing process and you will pick them up from many different people over many years. (And even then people will still argue over some of them hehe). – Galik Oct 11 '14 at 22:16
  • Yeah, I guess that's mainly what I want out of this. I just wanna be as prepared as possible. And yeah I try to keep an open mind with her teaching style, considering she has told us to always opt for arrays over vectors. – user3857017 Oct 11 '14 at 22:36
  • 1
    It upsets me how professors teach *what* to do, penalize you for not doing it, and not saying *why*. The `using` keyword has the potential to cause a **lot** of problems; I try never to use it (which yes, means very verbose code in most cases). – Qix - MONICA WAS MISTREATED Oct 12 '14 at 01:04

4 Answers4

3

This is really one of those things that you can discuss over beer for hours and hours, and still not have an answer everyone is happy with.

If you are nearly always using std:: functionality, then adding using namespace std; at the beginning of the file is not that bad an idea. On the other hand, if you are using things from more than one namespace (e.g. writing a compiler using llvm:: and also using std::, it may get confusing as to which parts are part of llvm and which parts are std:: - so in my compilter project, I don't have a single file with using namespace ...; - instead I write out llvm:: and std:: as needed. There are several functions (unwisely, perhaps) called Type(), and some places use something->Type()->Type() to get the type-thing that I need... Yes, it confuses even me a little at times...

I also have many things that look like Constants::ConstDecl and Token::RightParen, so that I can quickly see "what is what". All of these COULD be made shorter and "simpler", but I prefer to see where things belong most of the time.

Being more verbose helps making it easier to see where things belong - but it makes for more typing and more reading, so it is a balance.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

I'd say that generally, you do not declare the use of std globally. I guess if you're making a simple application, that would suffice. However, when you work in a large organization you often times have different namespaces that are used, and those might have overlapping objects. If you have a function in std, and in a namespace that you created, and then call "using namespace std" AND "using namespace yournamespace", you'll get unwanted results when calling that function. When you prefix every call with the namespace, it keeps it clearer and doesn't give issues with overlap.

m1cky22
  • 208
  • 1
  • 6
  • 1
    Prefixing every call with the namespace is not a workable approach if you still want ADL to work, though. Given `using namespace std; template void Foo(T &a, T &b) { swap(a, b); }`, how would you change the call to `swap` to continue allowing ` `namespace N { struct S { }; void swap(S &, S &); }`, where `Foo` should call `N::swap` instead of `std::swap`? –  Oct 11 '14 at 21:34
  • 1
    For that, you do need `using`, but you can limit it to those functions you want instead of all of `namespace std`. –  Oct 11 '14 at 21:35
  • So, is a namespace sort of like the "place" something is being performed in? Like standard is just screen I/O? Through looking at some of the function definitions in libraries, I've seen what look like other ::xxx spaces, and assumed them to be for things like file I/O or program-to-program I/O? Please correct me if I'm wrong, because this is all uncovered ground for me. – user3857017 Oct 11 '14 at 21:35
  • 1
    @user3857017 The standard library puts pretty much everything in `std` directly. (Specific implementations of the standard library do internally use additional namespaces, but those are implementation-specific details that aren't generally intended for direct use by programs.) File access, threads, containers, they're all part of the `std` namespace. It could have been organised differently, with separate namespaces for file access, separate namespaces for container types, etc., and some other libraries do take that approach, but the standard library does not. –  Oct 11 '14 at 21:39
  • 2
    @user3857017 What you may have seen is class member accesses, which uses the same syntax as namespace member accesses. Given `A::B::C`, `A` could be either a namespace or a class, and if it is a namespace, `B` could be either a namespace or a class. There's no way to tell just from the syntax, you'd have to look up the names. And yes, in a way, classes like that can be used as sort of a namespace, but not exactly. –  Oct 11 '14 at 21:43
  • What exactly does a namespace provide then? Is it like a set of categories or "bins" to sort information into? It's been mentioned here that you can make your own, so I would imagine that lets you tailor it to your specific needs on space or something? – user3857017 Oct 11 '14 at 21:44
  • @hvd I guess I really don't know what a class is (yeah now I'm feeling as though I've been taught nothing) so I can't really distinguish between the two. But it seems pretty likely. Although most have been in main alone with a ::std:: followed by a regular cout, cin, etc. – user3857017 Oct 11 '14 at 21:46
  • 1
    @user3857017 Ah, okay. Short answer: a namespace is just a way of grouping names to prevent conflicts. If you have one function `f()`, and another function `f()`, in languages that don't have namespaces, you simply have a conflict that cannot be resolved without renaming one of the functions. In languages that do have namespaces, the person defining the function has the option of putting it in a separate namespace, and if those two functions are not in the same namespace, you don't have a conflict, those functions can coexist. How namespaces are used is up to the person defining the functions. –  Oct 11 '14 at 21:48
  • 1
    @user3857017 Or: namespaces are to names what directories are to files. –  Oct 11 '14 at 21:50
  • @hvd That makes a lot of sense now, thanks for clearing that up. So assuming we continue the directory/file analogy; would it go library/namespace/function? Or is a namespace defined in a header? (Sorry if this is getting off topic but I'm interested and my book isn't satisfactory.) – user3857017 Oct 11 '14 at 21:58
  • 1
    @user3857017 No, it's just namespace/function, where it's up to the libraries to pick namespaces that are unlikely to conflict. The standard library uses puts most things in namespace `std`, and some things in the global namespace (the root directory). Boost is a well-known and widely used C++ library which puts most things in namespace `boost`. But a random third-party library might also have a (bad?) reason for putting things in that same namespace `boost`. It's up to the libraries to use sane namespaces, just as it is up to program installers to not install everything directly in C:\. –  Oct 11 '14 at 22:05
  • @hvd Ah, I think I get it now. I'll have to try and re-approach my searches from earlier to better understand it. Or maybe now I can just ask my professor about this and actually have a point to work from. You've been very helpful! Thanks a lot! – user3857017 Oct 11 '14 at 22:12
  • 1
    @user3857017 The best definition I've heard for a namespace is that it's a logical grouping of functions and objects. So the std:: namespace contains standard objects and functions, such as the stl containers, std::fill_n(), std::max(), std::sort(), etc., etc., etc. Likewise the boost:: namespace is everything in the boost libraries, and getting very specific boost::asio::ip::tcp:: are objects and functions that deal with TCP connections in the boost::asio:: library. – dgnuff Oct 11 '14 at 22:15
  • 1
    @user3857017 Taking a very concrete example, the server I work on has a `System` namespace that contains operating system specific routines. `System::Sleep(int microseconds)` takes a time in microseconds and sleeps for that long. By placing it in a namespace, we are able to avoid conflicts with the `Sleep()` routine present in Win32 which takes a time in milliseconds. So we never use `Sleep()` or `::Sleep()` in our code, because it won't compile with GCC under Linus, instead we only use `System:Sleep()` – dgnuff Oct 11 '14 at 22:22
  • @dgnuff So theoretically, and somewhat irresponsibly, the following `This::foo() That::foo() These::foo() Those::foo()` And all of the foo() calls would theoretically yield different results based on their definition in each namespace? – user3857017 Oct 11 '14 at 22:30
  • 1
    That's pretty much correct. I would not describe it as irresponsible either. Just as you might have class functions: `Square::Draw()`, `Circle::Draw()`, `Triangle::Draw()` each of which does something different, in your example the various `foo()` routines could do different things. The trick is to know when to use this feature of C++. When used properly it can make perfect sense. `boost::asio::ip::tcp::socket::send()` and `boost::asio::ip::udp::socket::send()` is an example where there are two `send()` methods, differentiated only by the namespaces they're in. – dgnuff Oct 12 '14 at 00:14
  • 1
    @user3857017 "What exactly does a namespace provide then?" One important difference I have not yet seen above is that classes and structs must be defined within one compilation unit (i.e. a .hpp file). Namespaces are more 'open', and can be contributed to in multiple files. For example, my namespace "DTB" has ~50 classes defined across ~30 .hpp files ... just as "std" has many classes within it. When I read code with a "DTB::" prefix, I know where to find (forgotten?) details. – 2785528 Oct 12 '14 at 01:02
1

general why?

Naming things is one of the more difficult aspects of software development. Beginners simply have little idea of how their name choices might generate ambiguities later on.

In particular, our software jargon often has preferred terms for certain issues. These preferences can cause unrelated class instances to be developed with the same (or similar) symbol with similar meanings.

Some of my often used symbols include init(), exec(), load(), store(), and I use timeStampGet() lots of places. I also use open(), close(), send()/recv() or write()/read().

So, I could rename init() in each of the 3 name spaces, and 5 objects into which I have added it, but it is much simpler to specify which one I want.
I find exec() in 2 name spaces and 12 objects. And there are 3 different timeStampGet() methods that I use. Whether namespaces or functions or class methods, these symbols make sense to me.

Furthermore, I find the 5 char "std::" namespace-as-prefix completely natural, and much preferable to the global "using namespace std". I suppose this comes with practice.

One more item - any where a larger name space or class name becomes tiresome, I sometimes add a typedef short name ... here are some examples from production code:

typedef ALARM_HISTORY   ALM_HST;
typedef MONITOR_ITEM    MI
typedef BACKUP_CONTROL  BC;

On one team, we agreed to use well defined 'full' names, which, occasionally, became tiresome because of the length. Later in the project, we agreed that typedefs (for short class or namespace names) could be used when they were simple and added no confusion.

2785528
  • 5,438
  • 2
  • 18
  • 20
1

Personally I hate 'using' declarations. To me they make code unreadable and you break namespaces. I've spent 20 years as a maintenance programmer and I hate anything that make the code harder to read - in my mind using is as useless as throw specifications.

What is more readable 6months - a year - 10 years down the line

UDP::Socket sock
sock.send(data)
TCP::Socket sock2
sock2.send(data)

vs

using UDP;
using TCP;
sock.send(data)
sock2.end(data)

I also don't like namespace aliases

using namespace po = boost::program_options; 

Now you are making the next programmer work harder with an extra level of indirection looking up what po is compared to boost::program_options. Same goes for those horrible typedef of

typedef long QUADWORD;

What size is a quadword - how long is a long 4 bytes? 8 bytes maybe 17 bytes on my OS

My last take is if you cannot type then don't be a programmer - a saved keystroke != good maintainable code

Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77