+ 2
Using namespace std;
Why do we write it in C++ ?
2 odpowiedzi
+ 10
Let's start with a problem to explain what namespaces are. We all know that we can't have functions, classes or any other kind of data that have the same name. Let's say that we have two libraries that both add a function, let's say print(). They both give a different function, but in naming they are indistinguishable. That's where namespaces come in. A namespace is like adding a new group name to which you can add functions and other data, so that it will become distinguishable.
namespace bla { void print() { // function bla::print() } } namespace blabla { void print() { // function blabla::print() } }
Now, as you can see, there are two functions with the name print, yet there is no naming conflict, because of namespaces. The first function would be called by using: bla::print() and the second with blabla::print().
std is an abbreviation of standard. std is the standard namespace. cout, cin and a lot of other things are defined in it. (This means that one way to call them is by using std::cout and std::cin.)
The keyword using technically means, use this whenever you can. This refers, in this case, to the std namespace. So whenever the computer comes across cout, cin, endl or anything of that matter, it will read it as std::cout, std::cin or std::endl.
When you don't use the std namespace, the computer will try to call cout or cin as if it weren't defined in a namespace (as most functions in your codes). Since it doesn't exist there, the computer tries to call something that doesn't exist! Hence, an error occurs.
If you have any trouble understanding the above, please tell me and I will try to clarify.
@Sololearn
+ 2
Beautifully explained ☺️