Skip to main content

Better Alternatives for ‘using namespace std’ in C++ Neeraj Mishra The Crazy Programmer

Most new C++ programming students are taught to add “using namespace std” in the global scope after introducing the headers needed for their programs to compile successfully. As a result, students grow accustomed to engaging in this practice without realizing how bad it is. Including ‘using namespace std’ in the global scope is bad practice. Some programmers are simply unaware of this, while others find it less demanding to add that statement in the global scope.

With online learning becoming increasingly prevalent, especially for aspiring programmers, it’s easy to learn bad coding practices because there’s no way to understand the author’s skill level. In other instances, people do know what to do but prefer the easy option. However, there are many downsides of adding this simple statement while coding. It’s worth finding out why so that you do not end up like me and run into a more experienced supervisor who frowns at its use.

This article provides information about “using namespace std” and why it is a bad idea to add it in the global scope. It also proposes better alternatives that can be adopted in its stead.

What is using namespace std?

I remember rolling my eyes while reading a blog post some time ago after seeing someone write code that read like this:

std:cout << “you” << std:endl << std::lcm(2, 2) << std::gcd(3, 7) …ad infinitum;

In my head, I was thinking “Pftt! I mean who does this? I hope you know that you can simply write ‘using namespace std’ instead of engaging in this tedious, repetitive, boring task.” I probably also laughed at the ridiculousness of it. Well, who would have thought that I’d be here writing an article about why you should try to write code in the same way? Definitely not me.

So, what is ‘using namespace std?’ Someone less experienced (like the version of me that existed two weeks ago) might define it as the statement one must add to their header file if they want to avoid encountering certain really nasty, headache-inducing errors. On the other hand, a more experienced programmer might begin to break it down to aid understanding like this: “first, std is short for standard, and the keyword ‘using’ specifies that the standard namespace should be used whenever possible. The keyword ‘namespace’ helps distinguish between different identifiers, and its use is supposed to prevent name collision. Hence, it is important to make use of namespaces in your program so that you don’t run into compile errors. With ‘using namespace std’ however, if an identifier is not found in the global scope the compiler will look in the standard library scope instead. This has its downsides and should be avoided at all costs.”

In short, it will be wise to listen to the second, a more experienced programmer who has his head screwed on straight.

Why you should avoid using namespace std in the global scope?

When ‘using namespace std’ is added to your code, the compiler will look for identifiers in the std:: namespace if it can’t find them in the global namespace. The maintainability of the program will decrease after making this inclusion since the whole content in the directive might not be needed and it can lead to confusion. This action is referred to as namespace pollution. Additionally, if anyone chooses to make use of the code you have written by including your header into their program, they will also inherit this ‘using’ behaviour, which is very likely not what they desire and may cause code breakages.

One key consequence of making this choice is that you might encounter name collisions in your program. To put it simply, name collisions occur when compilers can’t differentiate between identifiers. An example is when an identifier is added more than once. Let’s assume you write this code:

namespace std1 { 
        int someFunction(int) 
        { 
                /* Does something */ 
        } 
}

And you have another namespace written by someone else that also has the same function name. Somehow this code is imported into your program:

namespace std2 { 
        int someFunction(long int) 
        {
                /* Does something different*/ 
        } 
}

Finally, you add the following code to call the function.

using namespace std1; 
using namespace std2; 

int main() 
{
        someFunction(6); 
}

This will inadvertently lead to an issue because one function might be used in place of another. To make things worse, the compiler will not warn you, and it will be difficult for you to locate what the issue is. Talk about inducing headaches! Thus, it is better to make the effort to avoid this confusion. The better thing to do will be to specify which function is being referred to by writing std1::someFunction or std2::someFunction.

Better Alternatives for ‘using namespace std’

In this section, some alternatives that can be used in place of ‘using namespace std’ will be discussed. Embarcardero’s C++Builder will be used to show the different alternatives.

Instead of writing code in this manner:

namespace std 1

You can add only the directives needed in the local scope by doing this:

namespace std 2

Another common way is shown in the snippet below. Although it is a bit tedious, it is still a better way of writing code, and your supervisor will appreciate you for doing so:

namespace std 3

Conclusion

In conclusion, you should make an effort to use one of the methods shared above. It will not only prevent you from encountering name collisions and contributing to namespace pollution; it will also make you a better programmer. For some final parting words:

namespace std 4

This post is sponsored by Embarcadero, creator of the C++Builder, the powerful C++ IDE for multi-platform development focusing on database access and excellent UI design for all your platforms.

The post Better Alternatives for ‘using namespace std’ in C++ appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3r72hul

Comments

Popular posts from this blog

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet

2022: The year of hybrid work

Remote work was once considered a luxury to many, but in 2020, it became a necessity for a large portion of the workforce, as the scary and unknown COVID-19 virus sickened and even took the lives of so many people around the world.  Some workers were able to thrive in a remote setting, while others felt isolated and struggled to keep up a balance between their work and home lives. Last year saw the availability of life-saving vaccines, so companies were able to start having the conversation about what to do next. Should they keep everyone remote? Should they go back to working in the office full time? Or should they do something in between? Enter hybrid work, which offers a mix of the two. A Fall 2021 study conducted by Google revealed that over 75% of survey respondents expect hybrid work to become a standard practice within their organization within the next three years.  Thus, two years after the world abruptly shifted to widespread adoption of remote work, we are declaring 20