What is "using namespace::std" in C++ - c++

I am reading some code snippets from others and I find a line:
using namespace::std;
I suspect its purpose is using namespace std;, with some typos. But to my surprise the compiler accepts this code without any complaint. I build with:
$ g++ --version
g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
$ /usr/bin/g++ ${SRC} -std=c++11 -pthread -Wall -Wno-deprecated -o ${OUT}
I wonder why is this code valid, and what effects will it make? I suspect it is a bad practice.

It's equivalent to using namespace ::std; and also equivalent to using namespace std;. The :: refers to the global namespace, and std is put in the global namespace indeed.
As the syntax of using-directives:
(emphasis mine)
attr(optional) using namespace nested-name-specifier(optional) namespace-name ;
... ...
nested-name-specifier - a sequence of names and scope resolution
operators ::, ending with a scope resolution operator. A single ::
refers to the global namespace.
... ...

using namespace::std is the same as using namespace std;
The :: symbol is the scope resolution operator. When used without a scope name before it , it refers to the global namespace. This means that std is a top level namespace, and is not enclosed in another.
The spaces before and after the :: are optional in this case because the lexer can deduce the tokens from the context.
For example, all of the following are valid:
namespace A { namespace notstd{} } // define my own namespaces A and A::notstd
using namespace::std; // the standard library std
using namespace A;
using namespace ::A;
using namespace::A;
using namespace A::notstd;
Update:
As noted in one of the comments, using namespace ::std; and using namespace std; may actually lead to different results if the statement comes inside another namespace which contains its own nested namespace std. See the following (highly unlikely) example:
#include <stdio.h>
namespace A {
namespace std {
int cout = 5;
}
using namespace std;
void f1() {
cout++;
}
}
int main()
{
A::f1();
printf("%d\n",A::std::cout); // prints 6
return 0;
}

Related

C++: using namespace directive for non-existing namespace [duplicate]

This question already has answers here:
"using namespace std;" without any #include? [duplicate]
(3 answers)
Closed 2 years ago.
I am tryting to compile following code with g++ (version 7.5.0)
using namespace nspace;
int main()
{
return 0;
}
It gives error as follow
$ g++ above_code.cpp
namespaces_mystery1.cpp:1:17: error: ‘nspace’ is not a namespace-name
using namespace nspace;
^~~~~~
namespaces_mystery1.cpp:1:23: error: expected namespace-name before ‘;’ token
using namespace nspace;
^
Above behaviour is what I have expected.
But when I try to compile following code, it compiles fine without error like above.
using namespace std;
int main()
{
return 0;
}
Why this different behaviour for namespace named std compared to namespace named nspace
The namespace nspace doesn't exist at the point using namespace nspace; is encountered, whereas the std namespace does. The latter could be true due to implicit or explicit inclusion of facets of the C++ standard library, or the compiler itself might even hardcode it.
If you had written
namespace nspace{}
before the using statement, then compilation would succeed.

What does using namespace std; do?

What is the matter with this C++ code?
I get an error message saying: that there should be a ; before z, which is not correct. The only part that I don't understand is the purpose line 2 serves.
#include <iostream>
using namespace std;
int subtraction(int a, int b)
{
int r;
r=a-b;
return r;
}
int main()
{
int z;
z = subtraction (5,9);
cout z;
}
Thank you in advance.
using namespace std; means you can write cout later on rather than std::cout. It saves typing at the expense of gross namespace pollution.
Your compile error can be fixed by writing cout << z;
Also, do return a value from main.
To begin to explain what this does, it is important for you to understand what namespaces do. Namespaces are logical units of code divided up, you are able to create your own namespace or use other namespaces. The benefit of using namespaces is to have your program logically divide up your code with like functions. This is very similar to classes, but you do not need initiation of the namespaces like classes do. IN Java this would be similar to packages. To use a function within a namespace you need to use the namespace identifier followed by the function you are calling. This will call the correct function in the namespace scope you are wanting to use. An example of creating a namespace is the following:
namespace connection
{
int create_connection();
int close_connection();
//ect.......
}
Then later in the code when you want to call create_connection you need to do it the following way:
connection::create_connection();
As for your answer you are able to prevent from having to type the namespace identifier in this case connection, or in your case std. You are able to introduce an entire namespace into a section of code by using a using-directive. This will allow you to call the functions that are in that namespace without needing to use the namespace followed with the scope indicator" :: ".
The following syntax to do this is as follows:
using namespace connection:
or in your case
using namespace std;
So by doing this with std you will be granting that access to std namespace which includes C++ I/O objects cout and cin to use freely without having to use the namespace and scope operator first. Though a better practice is to limit the scope to the namespace members you want to actually use. On large programs this will be cleaner why of coding as well as avoid several problems. To introduce only specific members of a namespace, such as only introducing the std::cin and std::cout, you do the following:
using std::cin;
using std::cout;
What does using namespace std; do?
It tells the compiler which class/namespace to look in for an identifier. You either use using namespace std; in the beginning of the file or have to place it in front of each function that belongs to it.
What is the matter with this C++ code?
The syntax to use std::cout is:
std::cout << source;
variable source is inserted with the help of operator << in the std::cout stream which prints it to the standard output, i.e. computer monitor.
std "labels" a function member of the Standard Library. This is a technique used (among other reasons) to resolve (using the resolution operator ::) members that belong to the Standard Library from (possible) name conflicts with functions with similar(same) names and to reduce a scope of a search. std is called a namespace, so using namespace std; is a bit self explanatory.

Is it ok to wrap code in anonymous namespaces for using directives? [duplicate]

This question already has answers here:
Is using namespace in an anonymous namespace safe?
(2 answers)
Closed 3 months ago.
I want using namespace std; to apply to classes as well as functions without polluting the global namespace, but I'm wondering if it's an ok approach.
namespace
{
using namespace std;
class S
{
public:
S()
{
cout << "ok";
}
friend ostream operator<<(ostream& os, const S& s);
};
}
Any caveats to this?
It will work but keep in mind the following points:
You should limit its use in a source file, not in a header file (in general you should refrain from using unnamed namespaces in headers since they can easily mess around with your symbol definitions, especially if there are inline functions that use something from the anonymous namespace).
It's a bad practice and adding an additional naming hierarchy layer (i.e. the anonymous namespace) just for laziness is as bad as it sounds.
If it's in header file then it's not preferable as this file could be included in multiple source file. If in some source file then its acceptable
Whilst this looked like a great solution, in my experiments it doesn't do as I expected it would. It doesn't limit the scope of the using directive.
Consider this:
#include <string>
namespace {
string s1; // compile error
}
namespace {
string s2; // compile error
}
string s3; // compile error
int main()
{
}
None of those strings compile because they are not properly qualified. This is what we expect.
Then consider this:
#include <string>
namespace {
using namespace std;
string s1; // compiles fine (as expected)
}
namespace {
string t2; // compiles fine (I didn't expect that)
}
string v3; // compiles fine (I didn't expect that either)
int main()
{
}
So placing a using directive within an unnamed namespace appears to be exactly the same as placing it in the global namespace.
EDIT: Actually, placing a symbol in an unnamed namespace makes it local to the translation unit. So this is why it can't work for the intended purpose.
Therefore it has to be a no-no for headers.
An unnamed namespace doesn't contain the effects of a using-directive:
namespace A {int i;}
namespace {
using namespace A;
}
int j=i,k=::i; // OK
Both qualified and unqualified lookup follow the implicit using-directive for the unnamed namespace and then follow the explicit one within it. Wrapping the unnamed namespace inside another namespace limits the unqualified case to other code within that outer namespace, of course:
namespace A {int i;}
namespace B {
namespace {
using namespace A;
}
int j=i; // OK, as above
}
int j=i, // error: i not found
k=B::i; // OK
However, in either case you might as well write the using-directive outside the unnamed namespace (or not write it at all if it would be problematic, perhaps because it would appear in a header file).
Don't take the decision to use an anonymous namespace just so you can limit the scope of a using directive.
That being said, if an anonymous (or any other) namespace is already there and you want the advantages of the using inside it, it's fine as long as your coding standards okay it.

Difference between 'using' and 'using namespace'

In the boost libraries, there are often examples of including the library like:
#pragma once
#include <boost/property_tree/ptree.hpp>
using boost::property_tree::ptree;
Throughout my program I have been importing namespaces like this:
#include "../MyClass.h"
using namespace MyClassNamespace;
Can someone please explain:
The difference between using and using namespace;
What the advantage of negating the use of using namespace in favour of using;
The differences in forward declaring using and using namespace;
Thanks
using namespace makes visible all the names of the namespace, instead stating using on a specific object of the namespace makes only that object visible.
#include <iostream>
void print(){
using std::cout;
using std::endl;
cout<<"test1"<<endl;
}
int main(){
using namespace std;
cout<<"hello"<<endl;
print();
return 0;
}
while using "using namespace std" all the elements under the scope of std are made available under scope of the function.
while using "using std::cout" we explicitly mention what element under the std is required for the function ,without importing all the elements under std.
this is my first answer in stack overflow please correct me if iam wrong!!

using namespace issue

When I use the following
#include <map>
using namespace LCDControl;
Any reference to the std namespace ends up being associated with the LCDControl name space.
For instance:
Generic.h:249: error: 'map' is not a member of 'LCDControl::std'
How do I get around this? I didn't see anything specific to this on any documentation I looked over. Most of them said not to use: using namespace std;.
Here's line 249:
for(std::map<std::string,Widget *>::iterator w = widgets_.begin();
It looks like there's a std namespace within LCDControl that's hiding the global std namespace. Try using ::std::map instead of std::map.
I would say that either there's a using namespace std somewhere within the LCDControl namespace, or possibly there's an #include of a STL header that defines std within the LCDControl namespace.
e.g.:
namespace LCDControl
{
#include <map>
}
Which would define all the symbols in <map> as part of LCDControl::std, which in turn would hide the global std, or at least any symbols defined in the inner namespace, I'm not sure.
When I tried this under VS2008, I got an error:
namespace testns
{
int x = 1;
}
namespace hider
{
namespace testns
{
int x = 2;
}
}
int y = testns::x;
using namespace hider;
int z = testns::x; // <= error C2872: 'testns' : ambiguous symbol
The 'map' class lives in the std namespace, so you are going to have to qualify that somewhere. How are you qualifying your map object? You should have no problem doing this:
std::map<foo> myMap;
You can also do something like this if you do not want to explicitly qualify it every time, but also do not want to pollute your global namespace:
using std::map;