Risks of using a namespace

Hi!

As per the lecture indicates, here is a brief description of what problems may arise when using a “using namespace” statement in your code.

First of all, “using namespace” lets the programmer access certain functionalities that are part of that given namespace without having to type the full path to those functionalities. For instance, if we want to print out to the screen in a console command we would use something like the following statement:

std::cout << “Hello guys and girls!”;

Writing std::cout a bunch of times can be a bit of a nuisance, so many programmers prefer to use the neater statement:

cout << “Hello guys and girls!”;

In order do to so, we have to indicate that we are using the standard namespace somewhere in our code for the compiler to be able to understand that lonely cout statement. This is where the problems might arise if we can’t keep track of which namespaces are being used - if we are including multiple libraries into our files of code and we are employing the “using namespace” statement for all of them, we might run into the problem of those libraries having multiple versions of the same statement. For example, in the standard library “cout” does something very specific, whereas a different library might be using the same cout terminology for something different. If we only type cout, how do we make sure the compiler knows which one to use?

Hopefully that’s a viable explanation. Take care!

Privacy & Terms