using namespace std;

Today, I was tutoring a classmate for CS16, one of our beginning CS classes at UCSB. One of the first things that almost all the CS professors teach students to begin their C++ code with is using namespace std;. However, this is often without explanation of what is happening behind the scenes and I would argue that this is a horrible practice which leads students to have hidden bugs in their code.

To illustrate the problem with this, allow me to illustrate with an example of how using namespace std; leads students down a path of potential confusion. In the class, they were learning about pass-by-value, pass-by-pointer, and pass-by-reference. In the class, the following code was given:

#include <iostream>
using namespace std;

void swap(int *px, int *py) {
    int tmp = *px;
    *px = *py;
    *py = tmp;
}

int main(int argc, char **argv) {
    int x = 10, y = 20;
    cout << "Before:" << endl << x << " " << y << endl;
    swap(x, y);
    cout << "After:" << endl << x << " " << y << endl;
}

Now, if you noticed the way that swap is being invoked by main, you would quickly observe that this should be a compiler error since the swap function is expecting an int *, and you have passed it an int. However, if you run the code through a compiler, “magically” it works and you get the values that you expected!

What happened in the compiler was that the code utilized a built-in version of swap from std, making it “work”. This is only one simple example of how an error like this can confuse students and how having students blindly insert using namespace std; is a huge mistake waiting to happen.

Thus, I think it is a very bad idea to teach students to blindly use using namespace std; without understanding what it does to the students’ code. There are many functions in the std namespace, and it makes it extremely hard to detect errors in examples like this. And, in all honesty, learning to prefix things like cout and use std::cout is good practice and enhances students’ understanding of their code.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *