Skip to the content of the web site.

Lesson 216: What is the using keyword?

Previous lesson Next lesson


Up to this point, we have fastidiously prefixed every identifier from the standard library with std::. You may, however, have seen an alternate version of the Hello world! program

#include <iostream>
using namespace std;

int main();

int main() {
	cout << "Hello world!" << endl;

	return 0;
}

Note that we may now replace std::cout with cout and std::endl with endl. Isn't this easier to code (fewer characters)?

The using keyword tells the compiler to try to prefix every identifier with std:: first, see if this resolves to something within the std namespace (in this case, in iostream), and if not, just treat the identifier as an identifier.

The problem here is that the entire point of namespaces is to avoid the collision of identifiers, and thus using the using keyword actually destroys all protections imparted by namespaces.

Critical warning:

Never use using in any production code, ever.

If you have a very long name space identifier and you don't always want to refer to that namespace, but you still want the protections of namespaces, you are welcome to use:

namespace shorter = longer_namespace_name;

Now, everywhere that you used to refer to longer_namespace_name::x, you may now refer to shorter::x, only it is critical to ensure that shorter is not itself a namespace.


Previous lesson Next lesson