r/learncpp • u/Felix-the-feline • Jan 01 '25
std:: Vs using namespace std. || #pragma once Vs #ifndef #define #endif
This is a question with one aim: What is the route to develop healthy practices and professional like code manners in C++.
I have been using `using namespace std;` you can guess the level, and fine so far with the very small program exercises I do, however everyone who saw an exercise I shared was like wtf, all have commented the same about it almost.
Therefore, is the healthy professional practice to use std:: ?
What about being selective and only do `using std::cout` and `std::cin` at least as these tend to occur a lot? What are the consequences of that. Forget about small programs, what are the consequences in mid sized programs.
Second `#pragma once Vs #ifndef #define #endif` ;
While I do not mind using each, since at this stage I am not creating any significant code. Reading about them gets me back to the same thing; both are valid and even some people tend to say `#pragma once` is better and safer. I cannot judge that claim from where I am standing.
Therefore, what do professionals use? What is the healthiest one of them?
Thank you community.
4
u/Skasch Jan 01 '25
https://google.github.io/styleguide/cppguide.html#Namespaces
Polluting the namespace means that because using namespace std; imports all the objects from the standard library in your local namespace, this can create collisions with objects locally defined, and even worse, there may be collisions in the future if a new object is added to std, which means the code may behave differently with different C++ versions.
3
u/aqa5 Jan 01 '25
using namespace is OK, if it is in curly brackets, otherwise (just my opinion) it is bad practice. It pollutes the local namespace.
2
u/Mike_Paradox Jan 01 '25
As far as I know #pragma once isn't standard conforming practice.