+ 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?
2 Respostas
+ 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. 😉)
+ 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.