I have seen the syntax below in many places where STL classes are used without explicitly qualifying them with std::
. What is the advantage of the initial namespace std {}
? Why not just put using namespace std;
?
namespace std {}
using namespace std;
Explanation: It is known that “std” (abbreviation for the standard) is a namespace whose members are used in the program. So the members of the “std” namespace are cout, cin, endl, etc. This namespace is present in the iostream. h header file.
So when we run a program to print something, “using namespace std” says if you find something that is not declared in the current scope go and check std. using namespace std; are used. It is because computer needs to know the code for the cout, cin functionalities and it needs to know which namespace they are defined.
In the global scope, it applies everywhere. In a local scope (i.e, only in main()), it will only apply in main. Put std:: before everything i.e, std::cout << "Hello, World!" << std::endl; Only use the specific thing you want inside a function.
why is it compulsory to use using namespace std ? It isn't. In fact, I would recommend against it. However, if you do not write using namespace std , then you need to fully qualify the names you use from the standard library.
namespace std {}
simply declares the namespace so that the compiler knows about it and doing using namespace std;
won't cause an error.
Later in the code stuff from std::
can be #include
d and they can be automatically referred to without the std::
prefix.
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