hi guys while I was reading codes I see some guys using std::cin
in their code
and so on. Why? Why not just use a global using namespace std; ? is there a drawback to using it globally? And if yes can u explain why?Or if there is not why are they using it like that?
Thanks a lot.
P.S. I know that my questions might seem stupid but I just want to get as much good programming habits as possible when I'm learning cus I don't want to hit my head against the wall when I start coding something complex.
I think the main reason people don't do it is so they don't pollute the global namespace with loads of names that they won't use, and may potentially lead to clashing of names.
Just find it so much easier to write cin >> rather than std::cin. So far ive never had a problem with it.
I used to be like that, turns out you're just lazy aswell.
I stopped using it because I was advised by Helios. I don't completely know why he doesn't advise using it but from what I gather as Chewbob said, it contains functions and what not with names that might clash with ones you might use (count for example) and adds in extra stuff to your program that you probably won't need/use.
However, I'm not completely satisfied with that answer.
The real difference is whether or not your using declarations will ever contaminate someone else's namespace(s), which you should never do.
So, in header files, please don't ever use it.
In cpp files, it is up to you and your team as to whether it will cause a problem.
While on the subject of namespaces, when creating library files, it is always a good idea to wrap your own stuff (even private objects) in a unique namespace of your own. This prevents namespace clashes between your library code and other's library code when linking. (Such things have happened.)
My personal opinion on the matter is that
1. It's easier to see where functions are coming from if it's std::standardFunction() instead of just standardFunction().
2. Are you really going to use EVERYTHING in the std namespace?
3. It avoids naming errors if you don't use it.
Never use usingnamespace std unless you're porting code from the old iostream library.
What you do with programs written and maintained by yourself is not the kind of program I'm talking about.
But C and C++ are designed to enable team development of programs that have 10+ year lifetimes and worked on my many people over the years by people of varying skill, and over the period when many new technologies and libraries are introduced.
Don't take shortcuts, they always come back to haunt you.