6

Why we need both the "header file" and the using namespace tag for the any library function to get executed properly. For example cout will not work unless we use iostream. Also it will not work unless we use "using namespace std". My question is why do we need combination of both using namespace std as well as #include <iostream> for cout to execute successfully?

Unbreakable
  • 7,776
  • 24
  • 90
  • 171
  • 2
    When I started c++, I was wondering this too. – Irrational Person Dec 21 '14 at 05:54
  • You really don't "need" `using namespace std;`. In fact, you're better off not using it in most situations. See http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – juanchopanza Dec 21 '14 at 08:01
  • 1
    what I asked basically was why to use "using namespace std" or in your case " std::cout " when we had already added iostream. I did not ask for which one is better " using namespace std" or the std::cout .Anyways Thanks. – Unbreakable Dec 21 '14 at 08:08
  • And the link tells you the there is no "why". It is a bad idea so you should avoid it. – juanchopanza Dec 21 '14 at 08:10

3 Answers3

7

Including a library header makes the library feature visible to your program code. Without that, your program has no idea that the library even exists. This is the part that is necessary.

Writing using namespace std simply allows you to write cout rather than the full name which is std::cout. It's a convenience, that's all.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
4

cout is defined in the std namespace, and you can use it without adding a using namespace like

std::cout << "Hello, World" << std::endl;
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thanks for the reply. But my question is why do we need it in the first place. Since once we exposed "iostream" then why can't we simply use cout. Why to use std::cout or using namespace std. – Unbreakable Dec 21 '14 at 05:44
  • 4
    Namespaces were added to the language. They allow you to reduce and or eliminate variable name collisions. What if you wrote your own class named string? Or a variable named cin? – Elliott Frisch Dec 21 '14 at 05:50
3

Thanks for the reply. But my question is why do we need it in the first place.
Since once we exposed "iostream" then why can't we simply use cout.

Why to use std::cout or using namespace std?

When you don't use the std namespace, compiler will try to call cout or cin as if it weren't defined in a namespace. Since it doesn't exist there, compiler tries to call something that doesn't exist! Hence, an error occurs.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
user1
  • 4,031
  • 8
  • 37
  • 66