0

I'm used to

using namespace std;

which will make symbols from std available so I can type string mystring instead of std::string mystring.

But while reading some code today I found using namespace::std; (with double colon) in a header file. How does it differ from using namespace std;?

I'm aware using namespace std; should not be used on header files, but what about using namespace::std;?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • It's `using namespace ::std`. – Karl Knechtel May 06 '21 at 03:26
  • 3
    The C++ standard specifies that *"all library entities are defined within namespace std."*... So all of your standard C++ library functions, etc.. are exposed through namespace std. As for the `using namespace std;` shortcut, see [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/364696) – David C. Rankin May 06 '21 at 03:51

1 Answers1

1

OK! Let me clear your doubt with full explanation.

First of all, let's take a look at the syntax below and then I will describe it and will reach to the reason for using it:

using namespace std;

Here, the keyword using technically means, to use this whenever you can.

Now let's understand what namespace std is:

std is an abbreviation of "standard". std is the "standard namespace". cout, cin and a lot of other functions are defined within it.

The reason for using this:

When you don't use the std namespace, the compiler will try to call cout or cin as if they aren't defined in a namespace (like 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. So, essentially, without using namespace std; when you try to write cout << value; you have have to put std::cout << value;. By, adding this syntax to your preprocessor, you get free from adding std:: again and again, and also reduces the chances of any syntax error, as the compiler is instructed before the runtime that we are intended to use a std namespace whenever we can.

Here, are two examples for you given below:

// Without 'using namespace std;'
#include <iostream> 
 
int main() 
{ 
    std::cout << "Hello World\n"; 
    return 0;     
}

Now, let's see the benefit of using namespace std; :

// With 'using namespace std;'
#include <iostream> 
 
using namespace std; //now we don't need to write 'std::' anymore. 
 
int main() 
{ 
    cout << "Hello World"; 
    return 0;     
}

And, at last let me correct you at one point when we add this in preprocessor we use the syntax:

using namespace std;

not:

using namespace::std;

I hope so that this explanation would be helpful for you. Please, if it was helpful do upvote this.

Thank You!

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982