0

Since we are including the iostream header, what was the need to define cin, cout, endl, etc. inside the std namespace?

What added advantage did this cause?

Example: In C, we use to include stdio header file and used to call printf() and scanf() directly.

(I am aware namespaces is a C++ feature, the example is just to point at my confusion to understand its usage).

Edit : What would happen if cin, cout, etc. weren't a part of any namespace and we could just use them directly by just importing the header file. What problems would that cause?

13
  • These are standards commands, why shouldn't they be in the standard (std) namespace? Commented Sep 15, 2020 at 12:06
  • Separation of concern perhaps? Separation of symbols? Minimizing name-collisions? Commented Sep 15, 2020 at 12:06
  • 1
    namespaces are to organize names. You can have std::foo and my_lib::foo and the names don't clash. Actually I have no clue how C deals with that Commented Sep 15, 2020 at 12:09
  • 1
    @idclev463035818 it doesn't. Much pain may ensue. Commented Sep 15, 2020 at 12:09
  • 2
    Fun fact, C++ didn't have namespaces from the onset (though they were in the first published standard). There are legacy C++ codebases in the wild today that bear the mark of using the C way to avoid name collisions. It's not pretty. Commented Sep 15, 2020 at 12:23

1 Answer 1

4

It stops pollution of the global namespace. This is a headache in C and a lot of potential pitfalls have grown up: e.g. everything beginning with str is reserved in C. Furthermore it allows the C++ standard to define behaviour around std:: - for example, you are not allowed to add things to std with a few exceptions.

By and large then the global namespace is at the mercy of the programmer.

Sign up to request clarification or add additional context in comments.

5 Comments

What are the exceptions?
@M.A Special specializations of std::hash.
Can you please elaborate on 'It stops pollution of the global namespace?'
@AsteroidsWithWings yeah, the circle drawn by your answer is bigger :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.