What is using namespace std;
in recent C++?
In old compilers such as Turbo C++, this appears to be unsupported as it causes a compiler error. In more recent C++ compilers, this is the only method for compiling and running the program.
What is using namespace std;
in recent C++?
In old compilers such as Turbo C++, this appears to be unsupported as it causes a compiler error. In more recent C++ compilers, this is the only method for compiling and running the program.
Turbo C++ is a 20+ year old compiler. You shouldn't be using it.
That said,
#include <iostream>
using namespace std;
in a modern compiler is the same as writing the following in Turbo C for the standard headers.
#include <iostream.h>
Turbo C++ is pre-namespaces. So all standard headers are not in namespace std
. So you don't need the using namespace std
.
You will never need using namespace std
in Turbo C++ because it doesn't support namespaces. Turbo C++ doesn't support probably 50% of C++ stuff - it's that old. Use Visual C++ (Express editions are free) or G++ for C++.
C++ uses "namespaces" to group related classes and functions. The C++ Standard Library is almost entirely defined inside a namespace called std
(short for "standard"). When you #include
a standard header such as <string>
it contains definitions like this:
namespace std
{
template<typename T>
class allocator;
template<typename Ch>
class char_traits
{
// ...
};
template<typename Ch, typename Traits = char_traits<Ch>, typename Alloc = allcoator<Ch>>
class basic_string
{
// ...
};
typedef basic_string<char, char_traits<char>, allocator<char> > string;
}
The names allocator
, char_traits
, basic_string
and string
are all declared in namespace std
, so after including that header you need to refer to them as std::string
etc.
Alternatively, you can use a using-directive such as using namespace std
which makes all the names from namespace std
available in the current scope, so following the using-directive you can just say string
instead of std::string
.
The ancient TurboC++ compiler does not follow the standard, so its standard library just puts names in the global namespace, so you have to refer to string
not std::string
and you can't use using-directives. The first C++ standard was published in 1998, so you should not be using pre-standard compilers in 2013, it will not be a valuable education.
using namespace std;
tells the compiler that you don't care about the carefully designed use of std
in the standard library, but would rather deal with unpredictable and sometimes disastrous name conflicts on your own.
Don't use it. It is never necessary, even though some IDEs insert it automatically. If you have one of those, delete the declaration whenever it occurs.
To use names from the standard library, qualify then with std::
. Like this:
#include <iostream>
int main() {
std::cout << "Hello, world\n";
}