2

As far as I know, <iostream> header contains everything needed for input/output. But why we again write std:: namespace before cin like std::cin>>var;?

#include <iostream>

int main(int argc, char const *argv[]) {
    int var;
    std::cin>>var;
    return 0;
}
YSC
  • 38,212
  • 9
  • 96
  • 149
Rajan Raju
  • 113
  • 7

4 Answers4

4

The <iostream> header defines the variable cin inside the namespace std.

If you want to use it without prefixing the namespace, then you can use

using namespace std;

after including the header file, but then please read Why is “using namespace std;” considered bad practice?.

As a compromise you can do

using std::cin;

to only pull in std::cin itself into the current scope and nothing else.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Because every mechanism supplied by standard wrapped up by std namespace. In your case, it's I/O object cin.

You can skip entering std:: every time by placing using namespace std (bad case see: Using namespace std considired bad practice) or by placing using std::cin to use only one class (object) of the namespace.

Ladence
  • 244
  • 2
  • 9
2

But why we again write std:: namespace before cin like std::cin>>var;

It is a protection. This protects you. <iostream> and other standard includes define a lot (a LOT) of identifiers having really common names, e.g. sort, swap, list, transform, etc.

Without that protection, all those words would have to be reserved for the implementation. You don't want that.

YSC
  • 38,212
  • 9
  • 96
  • 149
1

Consider that you're looking for a person named John in a building. Finding the right John may be difficult since there may be more than one John in the building. It would be so much easier if you knew which room the right John is currently in.

In the same way, namespaces in C++ help us identify the right artifact being referred to. Think of cin as John and the namespace std as the room in the building. By using std::cin, we know that we're referring to the cin that is defined in the std namespace and not some other namespace.

hermit.crab
  • 852
  • 1
  • 8
  • 20