+ 5

Why do we add using namespace std in c++ code?

why do we add using namespace std in c++ code, and is it necessary to write it just below the header files?

6th Dec 2017, 12:43 AM
mythio
mythio - avatar
2 Antworten
+ 11
So we can use the standard namespace which allows you to use cin, cout, endl and other useful stuff. #include <iostream> using namespace std; int main(){ cout << "Hello World" << endl; } //Hello World Without namespace std you'll get an error: #include <iostream> int main(){ cout << "Hello World" << endl; } //Error: "cout" not declared within scope (Same for endl, by the way.) It is, however, not necessary and you can fix this another way (recommended when using multiple namespaces); #include <iostream> int main(){ std::cout << "Hello World" << std::endl; } //Hello World Hope this helped. (Also, I'm pretty sure there are many similar questions in the Q&A section, please check there before posting a question next time. 😉)
6th Dec 2017, 1:10 AM
blackcat1111
blackcat1111 - avatar
+ 7
It is so you don't have to keep writing std:: before every standard object. Without "using namespace std" you would have to write "std::cout" instead of just "cout," or "std::string" instead of just "string". The "using" directive can be put elsewhere, but you can't enjoy its benefits till it is in force.
6th Dec 2017, 1:16 AM
Eric Blinkidu
Eric Blinkidu - avatar