Pages

Friday, 10 June 2016

USING NAME STD IN C++

 Why is 'using namespace std' used

 Sep 3, 2011 at 3:48am
Hi,

I'm just starting to learn C++.
What I've learnt till date is we use <iostream> which contains everything needed for input/output.
Then also we need to type 'using namespace std' otherwise the code throws an error.

So my question is what is the necessity of using this namespace if everything is there in <iostream> for cout, cin etc..

I searched the net but everywhere the only thing i could find is the definition of 'namespace' and that 'namespace std' is a 'standard namespace'.

I would be glad if any of u Gurus kindly clarify my doubt. Many thanks in advance!

Regards,
Jaya
 Sep 3, 2011 at 4:01am
closed account (Gz64jE8b)
Without using namespace std; when you write for example cout <<; you'd have to put std::cout <<;

Here's a small example for you:

1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
    std::cout << "Hello World";
    system("pause");
    return 0;
    
}


1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World";
    system("pause");
    return 0;
    
}


They both do the exact same thing.
 Sep 3, 2011 at 4:04am
Let's start with a problem to explain what namespaces are. We all know that we can't have functions, classes or any other kind of data that have the same name. Let's say that we have two libraries that both add a function, let's say print(). They both give a different function, but in naming they are indistinguishable. That's where namespaces come in. A namespace is like adding a new group name to which you can add functions and other data, so that it will become distinguishable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace bla
{
  void print()
  {
    // function bla::print()
  }
}

namespace blabla
{
  void print()
  {
    // function blabla::print()
  }
}


Now, as you can see, there are two functions with the name print, yet there is no naming conflict, because of namespaces. The first function would be called by using: bla::print() and the second with blabla::print().

std is an abbreviation of standard. std is the standard namespace. cout, cin and a lot of other things are defined in it. (This means that one way to call them is by using std::cout and std::cin.)

The keyword using technically means, use this whenever you can. This refers, in this case, to the std namespace. So whenever the computer comes across cout, cin, endl or anything of that matter, it will read it as std::cout, std::cin or std::endl.

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

If you have any trouble understanding the above, please tell me and I will try to clarify.