using namespace std\n ...\ncout << "This is some text\\n";<\/code><\/pre>\n\n\n\nIt’s that simple. At least things should be that simple but it is not always the case.<\/p>\n\n\n\n
So Whats Wrong With “using namespace std”<\/h2>\n\n\n\n Well, this has nothing to do with performance but more of for lack of a better term… confusion. Lets us consider this.<\/p>\n\n\n\n
using namespace foo;\nusing namespace bar;<\/code><\/pre>\n\n\n\nSo from the above, we have assumed you are using two libraries called foo<\/em> and bar<\/em> respectively. We can assume there is a function called booboo()<\/code> in the foo<\/em> library and a couple of others too. In the bar<\/em> library there is a function called baabaa(<\/code>) and a couple of other unique functions too.<\/p>\n\n\n\nCalling either of these functions works just fine in this context. Now let’s complicate things a little. You decide to upgrade to the latest version of foo<\/em> with a barrage of new features and bug fixes. Unfortunately, the foo<\/em> library happens to include a new function called baabaa()<\/code>.<\/p>\n\n\n\nYou have just introduced a conflict. The new version of foo<\/em> and the existing bar<\/em>, both import baabaa() into the global namespace. As far as C++ is concerned, this is not acceptable and the compiler will surely complain about this. You can imagine the headaches you have to potentially deal with especially if you are working with a large codebase. The nightmare in fixing this issue will probably drive you up the wall depending on the size of the codebase.<\/p>\n\n\n\nThis could have been avoided if the original functions were called foo::booboo()<\/code> and bar:baabaa()<\/code>. No conflict there. You now have the option of enjoying the benefits of foo::baabaa()<\/code> too without the risk of complicating your code.<\/p>\n\n\n\nBe sure to avoid “using namespace<\/strong>” as much as possible. If you do use it and are aware of existing conflicts you can explicitly call the foo::baabaa()<\/code> and bar::baabaa()<\/code> where appropriate.<\/p>\n\n\n\nAnother way to gracefully handle this is to use specific tokens such as this:<\/p>\n\n\n\n
using std::cout<\/code> rather than using namespace std<\/code> if you are going to use a lot of cout<\/code> and know it will not cause conflicts.<\/p>\n","protected":false},"excerpt":{"rendered":"Every C++ programmer whether new or old is familiar with namespaces and more so “using namespace std”. In most C++ tutorials and courses this is taught early and with good…<\/p>\n","protected":false},"author":1,"featured_media":4149,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,27,16,17],"tags":[111,143,184,350,433,449,471,472,543,544,563],"yoast_head":"\n
Why is "using namespace std" Considered Bad Practice?<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n \n \n \n \n \n\t \n\t \n\t \n