Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need to specify "std" prefix?

Tags:

c++

std

I'm a beginner in programming and I often see many programs using the prefix std if they are using any std functions like std::cout, std::cin, etc. I was wondering what is it's purpose ? Is it just a way of good programming or is there more to it ? Does it make any difference for the compiler or is it readability or what ? Thanks.

like image 938
0x0 Avatar asked Mar 09 '11 00:03

0x0


People also ask

What is a STD prefix?

In subscriber trunk dialing, each designated region of a country is identified by a unique numerical code, the STD code, that must be dialed as a prefix to each telephone number when placing calls.

Why do we use STD?

It is known that “std” (abbreviation for the standard) is a namespace whose members are used in the program. So the members of the “std” namespace are cout, cin, endl, etc. This namespace is present in the iostream. h header file.

Why do we need namespace std?

So when we run a program to print something, “using namespace std” says if you find something that is not declared in the current scope go and check std. using namespace std; are used. It is because computer needs to know the code for the cout, cin functionalities and it needs to know which namespace they are defined.

Why do you need STD in C++?

The string and vector which we want to use are in the C++ standard library, so they belong to the std namespace. This is why you need to add std:: to them.


1 Answers

The STL types and functions are defined in the namespace named std. The std:: prefix is used to use the types without fully including the std namespace.

Option 1 (use the prefix)

#include <iostream>

void Example() {
  std::cout << "Hello World" << std::endl;
}

Option #2 (use the namespace)

#include <iostream>
using namespace std;

void Example() {
  cout << "Hello World" << endl;
}

Option #3 (use types individually)

#include <iostream>
using std::cout;
using std::endl;

void Example() {
    cout << "Hello World" << endl;
}

Note: There are other implications to including an entire C++ namespace (option #2) other than not having to prefix every type / method with std:: (especially if done within a header) file. Many C++ programmers avoid this practice and prefer #1 or #3.

like image 190
JaredPar Avatar answered Sep 23 '22 10:09

JaredPar