Why is it mandatory to use namespace std in new ID

2019-08-28 02:32发布

问题:

This question already has an answer here:

  • Why doesn't a simple “Hello World”-style program compile with Turbo C++? 3 answers

Why is it mandatory to use namespace std in new compilers whereas the programs written in Turbo C++/Borland C++ don't require namespace std ?

This works in old compilers

#include <iostream.h>

int main () {
   cout << "Hello Programmers";

   return 0;
}

but we have to write the below given program in new compilers instead of the above one, as the above programs don't work in new compilers.

#include <iostream>
using namespace std;

int main () {
   cout << "Hello Programmers";

   return 0;
}

回答1:

That's because turbo-c++ was released even before any c++ standard was released, and they didn't introduce a std namespace.

It was never updated since then.

Also it isn't mandatory to use the using namespace std; statement, but rather discouraged.

The code should be:

#include <iostream>

int main () {
   std::cout << "Hello Programmers";
}

or

#include <iostream>
int main () {
   using std::cout;    
   cout << "Hello Programmers";
}

Also IMO questions about turbo-c++ are quite futile this time. It's outdated and not remotely has to do anything with modern c++.
If your professors / teachers force you to use it1, tell them that they're doing it wrong and don't teach c++ in any way.


1)I know it's common at indian schools, but that's simply bad practice, and doesn't have a sound reasoning.
May be they want you to teach some things from scratch, because turbo-c++ doesn't support containers like std::vector or such.
But I still believe that's the wrong approach, because manual memory management is advanced stuff, and shouldn't be used to confuse beginners.



回答2:

I might be splitting hairs, but it is never mandatory to use using namespace std;. See here for why it is considered bad pratice.

Your first version may "work" in some ancient non-standard conformant compilers.

What you should do is write

#include <iostream>    
int main () {
   std::cout << "Hello Programmers";    
   return 0;
}

If you are lazy you could use

#include <iostream>
using std::cout;

int main () {
   cout << "Hello Programmers";
   return 0; 
}

And the version with using namespace std; is also technically correct, but it will lead to all sorts of nasty problems in bigger projects.



回答3:

First of all, it's not an IDE question, but a C++ compiler (C++ language implementation) question.

The first TurboC/BorlandC was shipped decades ago, when there were no namespaces intruduced in C++.