In C++, could I use using namespace std;
declaration in the function implementation files?
No you can't unuse a namespace. The only thing you can do is putting the using namespace -statement a block to limit it's scope. Maybe you can change the template which is used of your auto-generated headers.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
It doesn't affect the runtime performance at all.
It is not necessary to write namespaced, simply use scope resolution (::) every time uses the members of std. For example, std::cout, std::cin, std::endl etc.
Maybe you would like to know too that you can put using namespace std;
within a function body as well, like below. This will restrict the scope of the using namespace
statement.
void f() {
using namespace std;
cout << "Foo" << endl;
//..
};
void g() {
cout << "Bar" << endl; //ERROR: cout and endl are not declared in this scope.
};
This can be useful if you want to use a lot of elements of a namespace in the body of a function that is written in a header file (which you shouldn't per se, but sometimes it is OK or even almost necessary (e.g. templates)).
By "function implementation files" do you mean the .h files or the .cpp files? (I would normally call .cpp files "implementation" files, while .h files are "interface" files.)
If you mean, .cpp files, then of course. That is where you normally see using namespace std
. It means that all the code in this .cpp file has access to std
without qualification.
If you mean .h files, then you can, but you shouldn't. If you include it in a .h file, it will automatically apply to any .cpp file which includes the .h file, which could be a lot of files. You generally don't want to be telling other modules which namespaces to import. It is best to put it in every .cpp file rather than in a common .h file.
Edit: User @lachy suggested an edit which I won't include verbatim, but they suggested I point out that using namespace std
is usually considered bad practice, due to namespace pollution. They gave a link to a question on this topic: Why is "using namespace std;" considered bad practice?
I'm assuming you mean something like this:
// Foo.h
void SayHello();
...
// Foo.cpp
#include "Foo.h"
using namespace std;
void SayHello()
{
cout << "Hello, world!" << endl;
}
If that is the case, then yes. However, it's considered bad practice to use using namespace std;
in larger projects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With