for using cout
, I need to specify both:
#include<iostream>
and
using namespace std;
Where is cout
defined? in iostream
, correct? So, it is that iostream
itself is there in namespace std
?
What is the meaning of both the statements with respect to using cout
?
I am confused why we need to include them both.
iostream
is the name of the file where cout is defined. On the other hand, std
is a namespace, equivalent (in some sense) to Java's package.
cout is an instance defined in the iostream
file, inside the std namespace.
There could exist another cout
instance, in another namespace. So to indicate that you want to use the cout
instance from the std
namespace, you should write
std::cout
, indicating the scope.
std::cout<<"Hello world"<<std::endl;
To avoid the std::
everywhere, you can use the using
clause.
cout<<"Hello world"<<endl;
They are two different things. One indicates scope, the other does the actual inclusion of cout
.
Imagine that in iostream two instances named cout
exist, in different namespaces:
namespace std{
ostream cout;
}
namespace other{
float cout;//instance of another type.
}
After including <iostream>
, you'd still need to specify the namespace. The #include
statement doesn't say "Hey, use the cout in std::". That's what using
is for, to specify the scope.