I see a lot of people list code using this "::" as in:

#include <iostream>

int main()
{

    std::cout << "Blah, blah, blah";
    return 0;
}

and others use "using"

#include <iostream>

using namespace std;

int main()
{

    cout << "Blah, blah, blah";
    return 0;
}

Is there a downside to either, a reason to use one over the other?

The downside is that using namespace will make the entire namespace visible, even if you don't want all of the names to be visible. There's risk of naming clashes. Prefixing std:: is more verbose, but also imposes no risk of name clashes.

For namespace std, it's really just a matter of knowing what names are there and avoiding creating new names that match. But that's not as easy as it sounds, so the general best practice is to limit how many names you expose from a namespace.

Ah! Thank you!!

Here are some "safer" alternatives:

1) use the namespace only within a function body:

#include <iostream>

int main()
{
    using namespace std;
    cout << "Blah, blah, blah";
    return 0;
}

This limits the scope of the namespace usage, reducing the scope at which names could clash.

2) use the individual items instead of the whole namespace:

#include <iostream>

using std::cout; // at global scope

int main()
{
    using std::endl; // or at function scope

    cout << "Blah, blah, blah" << endl;

    return 0;
}

Again, this limits the name-clashes while reducing the verbosity when you only need a few elements of the namespace.

3) create a namespace alias:

#include <boost/program_options.hpp>

namespace po = boost::program_options;

int main(int argc, char** argv) {
  // use elements of the program_options namespace
  //  with po:: instead of boost::program_options::

  // ...

  return 0;
};

I had to show this with Boost.Program-Options, just as an example of a case when there can be a fairly long namespace name. Creating such an alias is a simple trick to reduce the verbosity.

This is so helpful, thanks!

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.