I tried following, it worked without problem, but in this situation, std was not defined.
using namespace std;
int main()
{
....
}
I tried following, it worked without problem, but in this situation, std was not defined.
using namespace std;
int main()
{
....
}
Your code is illegal. Directive using
can only nominate previously declared namespaces, i.e. namespaces whose names can be found by name lookup.
In this case your compiler apparently gives special treatment to name std
. It is a compiler-specific extension, which regards std
as an implicitly defined namespace. If your try a different namespace name in your code, it will most likely fail to compile.
All using namespace std
does is tell the compiler that, when an identifier (named variable, type, etc) appears in code, to look in the std
namespace for candidates to match the name.
Within your main()
function, no identifiers are being used at all (the {}
is an empty block). So there is no need to find matching candidates, and the result of compiling will be the same in both cases.
If you add a statement like cout << "Hello\n"
to main()
, then the using namespace std
will cause the compiler to consider anything named cout
within namespace std
as a valid match for the identifier cout
. If this comes after #include <iostream>
, then std::cout
is considered a viable match. If declarations in <iostream>
are not visible to the compiler (in your case, because there is no #include <iostream>
) then the compiler cannot consider std::cout
to be a candidate match for cout
, and will issue a diagnostic accordingly.
The C++ standard does not specify anything different about std
or about using directives that require using namespace std
and using namespace othername
to behave differently. If your compiler treats them differently (recognising namespace std
but not others, even if there is no declaration of one) then that is specific to your compiler.
Try and do std::cout, it won't work.
using namespace std
just defines the namespace
#include {x}
'includes' the code within the namespace
I.e, std::cout
would need #include <iostream>
. Very simple explanation but it's what is going on.