What does using namespace std; do? - c++

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.

Related

using namespace in c++

I have come to understand why using namespace std; is considered bad practice in c++
but let's consider for example 2 ( hypothetical ) libraries "std" and "sfd" , both of them contain a function "run()".
would the following be okay or is it still a problem :
( if i want to call "run()" from "std" )
using namespace std;
using namespace sfd;
int main(){
std::run();
}
( if i want to call "run()" from "sfd" )
using namespace std;
using namespace sfd;
int main(){
sfd::run();
}
There is no problem because you are using qualified names in the function calls.
A program would be ill-formed if you used the unqualified function name in its call like
run();
In this case there would be ambiguity.
The main purpose of using using namespace whatever; is to avoid typing the name of that namespace (like std and sfd) every time you want to have access to one of its members (for reasons such as saving time and also making the code look a bit cleaner). There is no problem with your solution though. It works.
But again, why would you want to use using namespace std; at the top of your source file if you're eventually going to add std:: to whichever function that needs it?
You can also write using namespace std; in a (function, loop, etc) scope so that it doesn't pollute the whole namespace of that particular source file.

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.

Using Namespace std

I am taking a programming class in school and I wanted to start doing some c++ programming out of class. My school using Microsoft Visual C++ 6.0 (which is from 1998) so it still uses <iostream.h> rather than <iostream> and using namespace std. When I started working, I couldn't figure out how and when to use using namespace std and when to just use things like std::cout<<"Hello World!"<<'\n'; (for example) as well as it's limits and other uses for the namespace keyword. In particular, if I want to make a program with iostream and iomanip, do I have to state "using namespace std" twice, or is there something different that I would have to use as well, or can I just do the same thing as I did with iostream? I tried googling it but I didn't really understand anything. Thanks in advance for the help.
Ok, handful of things there, but it is manageable.
First off, the difference between:
using namespace std;
...
cout << "Something" << endl;
And using
std::cout << "Something" << std::endl;
Is simply a matter of scope. Scope is just a fancy way of saying how the compiler recognizes names of variables and functions, among other things. A namespace does nothing more than add an extra layer of scope onto all variables within that namespace. When you type using namespace std, you are taking everything inside of the namespace std and moving it to the global scope, so that you can use the shorter cout instead of the more fully-qualified std::cout.
One thing to understand about namespaces is that they stretch across files. Both <iostream> and <iomanip> use the namespace std. Therefore, if you include both, then the declaration of using namespace std will operate on both files, and all symbols in both files will be moved to the global scope of your program (or a function's scope, if you used it inside a function).
There are going to be people who tell you "don't use using namespace std!!!!", but they rarely tell you why. Lets say that I have the following program, where all I am trying to do is define two integers and print them out:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int cout = 0;
int endl = 1;
cout << cout << endl << endl; // The compiler WILL freak out at this :)
return 0;
}
When I use using namespace std, I am opening the door for naming collisions. If I (by random chance), have named a variable to be the same thing as what was defined in a header, then your program will break, and you will have a tough time figuring out why.
I can write the same program as before (but get it to work) by not using the statement using namespace std:
#include <iostream>
int main(int argc, char** argv) {
int cout = 0;
int endl = 1;
std::cout << cout << endl << std::endl; // Compiler is happy, so I'm happy :)
return 0;
}
Hopefully this has clarified a few things.
If you use the header names without the .h, then the stuff declared/defined in it will be in the std namespace. You only have to use using namespace std; once in the scope where you want stuff imported in order to get everything; more than one using namespace std; doesn't help anything.
I'd recommend against using namespace std; in general, though. I prefer to say, for example, using std::cout; instead, in order to keep names in std from conflicting with mine.
For example:
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
int left = 1, right = 2;
cout << left << " to " << right << "\n";
}
may cause mysterious issues, because left and right exist in the std namespace (as IO manipulators), and they get imported if you lazily say using namespace std;. If you meant to actually use the IO manipulators rather than output the variables, you may be a bit disappointed. But the intent isn't obvious either way. Maybe you just forgot you have ints named left and right.
Instead, if you say
#include <iostream>
#include <iomanip>
int main()
{
using std::cout;
int left = 1, right = 2;
cout << left << " to " << right << "\n";
}
or
#include <iostream>
#include <iomanip>
int main()
{
int left = 1, right = 2;
std::cout << left << " to " << right << "\n";
}
everything works as expected. Plus, you get to see what you're actually using (which, in this case, includes nothing from <iomanip>), so it's easier to keep your includes trimmed down to just what you need.
Here is a good link that describes namespaces and how they work.
Both methods are correct, that is, you can either introduce a namespace with the "using" statement or you can qualify all the members of the namespace. Its a matter of coding style. I prefer qualifying with namespaces because it makes it clear to the reader in which namespace the function / class is defined.
Also, you do not have to introduce a namespace twice if you are including multiple files. One using statement is enough.
Good question, Ryan. What using namespace does is importing all symbols from a given namespace (scope) into the scope where it was used. For example, you can do the following:
namespace A {
struct foo {};
}
namespace B {
using namespace A;
struct bar : foo {};
}
In the above examples, all symbols in namespace A become visible in namespace B, like they were declared there.
This import has affect only for a given translation unit. So, for example, when in your implementation file (i.e. .cpp) you do using namespace std;, you basically import all symbols from std namespace into a global scope.
You can also import certain symbols rather than everything, for example:
using std::cout;
using std::endl;
You can do that in global scope, namespace scope or function scope, like this:
int main ()
{
using namespace std;
}
It is up to a programmer to decide when to use fully qualified names and when to use using keyword. Usually, it is a very bad taste to put using into a header files. Professional C++ programmers almost never do that, unless that is necessary to work around some issue or they are 100% sure it will not mess up type resolution for whoever use that header.
Inside the source file, however (nobody includes source files), it is OK to do any sort of using statements as long as there are no conflicting names in different namespaces. It is only a matter of taste. For example, if there are tons of symbols from different namespaces being used all over the code, I'd prefer at least some hints as for where they are actully declared. But everyone is familiar with STL, so using namespace std; should never do any harm.
There also could be some long namespaces, and namespace aliasing comes handy in those cases. For example, there is a Boost.Filesystem library that puts all of its symbols in boost::filesystem namespace. Using that namespace would be too much, so people usually do something like this:
namespace fs = boost::filesystem;
fs::foo ();
fs::bar ();
Also, it is almost OK to use namespace aliasing in headers, like this:
namespace MyLib {
namespace fs = boost::filesystem;
}
.. and benefit from less typing. What happens is that users that will use this header, will not import the whole filesystem library by saying using namespace MyLib;. But then, they will import "fs" namespace from your library that could conflict with something else. So it is better not to do it, but if you want it too badly, it is better than saying using namespace boost::filesystem there.
So getting back to your question. If you write a library using C++ I/O streams, it is better not to have any using statements in headers, and I'd go with using namespace std; in every cpp file. For example:
somefile.hpp:
namespace mylib {
class myfile : public std::fstream {
public:
myfile (const char *path);
// ...
};
}
somefile.cpp:
#include "somefile.hpp"
using namespace std;
using namespace mylib;
myfile::myfile (const char *path) : fstream (path)
{
// ...
}
Specific to using namespace std
You really shouldn't ever use it in a header file. By doing so, you've imported the entire 'std' into the global namespace for anyone who includes your header file, or for anyone else that includes a file that includes your file.
Using it inside a .cpp file, that's personal preference. I typically do not import the entire std into the global namespace, but there doesn't appear to be any harm in doing it yourself, to save a bit of typing.

include and using namespace in C++

for using cout, I need to specify both:
#include<iostream>
and
using namespace std;
Where is cout defined? in iostream, correct? So, it is that iostream itself is there in namespace std?
What is the meaning of both the statements with respect to using cout?
I am confused why we need to include them both.
iostream is the name of the file where cout is defined.
On the other hand, std is a namespace, equivalent (in some sense) to java's package.
cout is an instance defined in the iostream file, inside the std namespace.
There could exist another cout instance, in another namespace. So to indicate that you want to use the cout instance from the std namespace, you should write
std::cout, indicating the scope.
std::cout<<"Hello world"<<std::endl;
To avoid the std:: everywhere, you can use the using clause.
cout<<"Hello world"<<endl;
They are two different things. One indicates scope, the other does the actual inclusion of cout.
In response to your comment
Imagine that in iostream two instances named cout exist, in different namespaces
namespace std{
ostream cout;
}
namespace other{
float cout;//instance of another type.
}
After including <iostream>, you'd still need to specify the namespace. The #include statement doesnt say "Hey, use the cout in std::". Thats what using is for, to specify the scope
If your C++ implementation uses C style header files (many do) then there is a file that contains something similar to:
#include ... // bunches of other things included
namespace std {
... // various things
extern istream cin;
extern ostream cout;
extern ostream cerr;
... // various other things
}
std is the namespace that the C++ standard says most of the standard things should reside in. This is to keep from overpopulating the global namespace, which could cause you difficulty in coming up with names for your own classes, variables, and functions which aren't already used as names for standard things.
By saying
using namespace std;
you are telling the compiler that you want it to search in the namespace std in addition to the global namespace when looking up names.
If the compiler sees the source line:
return foo();
somewhere after the using namespace std; line it will look for foo in various different namespaces (similar to scopes) until it finds a foo that meets the requirements of that line. It searches namespaces in a certain order. First it looks in the local scope (which is really an unnamed namespace), then the next most local scope until over and over until outside of a function, then at the enclosing object's named things (methods, in this case), and then at global names (functions, in this case unless you've been silly and overloaded () which I'm ignoring), and then at the std namespace if you've used the using namespace std; line. I may have the last two in the wrong order (std may be searched before global), but you should avoid writing code that depends on that.
cout is logically defined within iostream. By logically, I mean it may actually be in the file iostream or it may be in some file included from iostream. Either way, including iostream is the correct way to get the definition of cout.
All symbols in iostream are in the namespace std. To make use the the cout symbol, you must tell the compiler how to find it (i.e. what namespace). You have a couple of choices:
// explicit
std::cout << std::endl;
// import one symbol into your namespace (other symbols must still be explicit)
using std::cout;
cout << std::endl;
// import the entire namespace
using namespace std;
cout << endl;
// shorten the namespace (not that interesting for standard, but can be useful
// for long namespace names)
namespace s = std;
s::cout << s::endl;
The #include <iostream> references the header file that defines cout. If you're going to use cout, then you will always need the include.
You do not need to using namespace std;. That's simply allows you to use the shorthand cout and endl and the like, rather than std::cout and std::endl where the namespace is explicit. Personally I prefer not to use using namespace ... since it requires me to be explicit in my meaning, though it is admittedly more verbose.

What requires me to declare "using namespace std;"?

This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare
using namespace std;
in C++ programs?
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive.
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;
Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::
Technically, you might be required to use using (for whole namespaces or individual names) to be able to use Argument Dependent Lookup.
Consider the two following functions that use swap().
#include <iostream>
#include <algorithm>
namespace zzz
{
struct X {};
void swap(zzz::X&, zzz::X&)
{
std::cout << "Swapping X\n";
}
}
template <class T>
void dumb_swap(T& a, T& b)
{
std::cout << "dumb_swap\n";
std::swap(a, b);
}
template <class T>
void smart_swap(T& a, T& b)
{
std::cout << "smart_swap\n";
using std::swap;
swap(a, b);
}
int main()
{
zzz::X a, b;
dumb_swap(a, b);
smart_swap(a, b);
int i, j;
dumb_swap(i, j);
smart_swap(i, j);
}
dumb_swap always calls std::swap - even though we'd rather prefer using zzz::swap for zzz::X objects.
smart_swap makes std::swap visible as a fall-back choice (e.g when called with ints), but since it doesn't fully qualify the name, zzz::swap will be used through ADL for zzz::X.
Subjectively, what forces me to use using namespace std; is writing code that uses all kinds of standard function objects, etc.
//copy numbers larger than 1 from stdin to stdout
remove_copy_if(
std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, "\n"),
std::bind2nd(std::less_equal<int>(), 0)
);
IMO, in code like this std:: just makes for line noise.
I wouldn't find using namespace std; a heinous crime in such cases, if it is used in the implementation file (but it can be even restricted to function scope, as in the swap example).
Definitely don't put the using statement in the header files. The reason is that this pollutes the namespace for other headers, which might be included after the offending one, potentially leading to errors in other headers which might not be under your control. (It also adds the surprise factor: people including the file might not be expecting all kinds of names to be visible.)
The ability to refer to members in the std namespace without the need to refer to std::member explicitly. For example:
#include <iostream>
using namespace std;
...
cout << "Hi" << endl;
vs.
#include <iostream>
...
std::cout << "Hi" << std::endl;
You should definitely not say:
using namespace std;
in your C++ headers, because that beats the whole point of using namespaces (doing that would constitute "namespace pollution"). Some useful resources on this topic are the following:
1) stackoverflow thread on Standard convention for using “std”
2) an article by Herb Sutter on Migrating to Namespaces
3) FAQ 27.5 from Marshall Cline's C++ Faq lite.
First of all, this is not required in C - C does not have namespaces. In C++, anything in the std namespace which includes most of the standard library. If you don't do this you have to access the members of the namespace explicitly like so:
std::cout << "I am accessing stdout" << std::endl;
Firstly, the using directive is never required in C since C does not support namespaces at all.
The using directive is never actually required in C++ since any of the items found in the namespace can be accessed directly by prefixing them with std:: instead. So, for example:
using namespace std;
string myString;
is equivalent to:
std::string myString;
Whether or not you choose to use it is a matter of preference, but exposing the entire std namespace to save a few keystrokes is generally considered bad form. An alternative method which only exposes particular items in the namespace is as follows:
using std::string;
string myString;
This allows you to expose only the items in the std namespace that you particularly need, without the risk of unintentionally exposing something you didn't intend to.
Namespaces are a way of wrapping code to avoid confusion and names from conflicting. For example:
File common1.h:
namespace intutils
{
int addNumbers(int a, int b)
{
return a + b;
}
}
Usage file:
#include "common1.h"
int main()
{
int five = 0;
five = addNumbers(2, 3); // Will fail to compile since the function is in a different namespace.
five = intutils::addNumbers(2, 3); // Will compile since you have made explicit which namespace the function is contained within.
using namespace intutils;
five = addNumbers(2, 3); // Will compile because the previous line tells the compiler that if in doubt it should check the "intutils" namespace.
}
So, when you write using namespace std all you are doing is telling the compiler that if in doubt it should look in the std namespace for functions, etc., which it can't find definitions for. This is commonly used in example (and production) code simply because it makes typing common functions, etc. like cout is quicker than having to fully qualify each one as std::cout.
You never have to declare using namespace std; using it is is bad practice and you should use std:: if you don't want to type std:: always you could do something like this in some cases:
using std::cout;
By using std:: you can also tell which part of your program uses the standard library and which doesn't. Which is even more important that there might be conflicts with other functions which get included.
Rgds
Layne
All the files in the C++ standard library declare all of its entities within the std namespace.
e.g: To use cin,cout defined in iostream
Alternatives:
using std::cout;
using std::endl;
cout << "Hello" << endl;
std::cout << "Hello" << std::endl;
Nothing requires you to do -- unless you are implementer of C++ Standard Library and you want to avoid code duplication when declaring header files in both "new" and "old" style:
// cstdio
namespace std
{
// ...
int printf(const char* ...);
// ...
}
.
// stdio.h
#include <cstdio>
using namespace std;
Well, of course example is somewhat contrived (you could equally well use plain <stdio.h> and put it all in std in <cstdio>), but Bjarne Stroustrup shows this example in his The C++ Programming Language.
It's used whenever you're using something that is declared within a namespace. The C++ standard library is declared within the namespace std. Therefore you have to do
using namespace std;
unless you want to specify the namespace when calling functions within another namespace, like so:
std::cout << "cout is declared within the namespace std";
You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.