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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With