Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `using namespace std;`, and why do I need it to compile programs with recent C++ compilers? [closed]

Tags:

c++

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.

like image 286
darla_sud Avatar asked Oct 27 '13 12:10

darla_sud


1 Answers

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.

like image 58
Jonathan Wakely Avatar answered Oct 05 '22 23:10

Jonathan Wakely