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.
Related
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having...
using namespace xyzzy
...statements in them, which impact on my code when I least want or expect it.
Is there a way I can somehow cancel/override a previous "using" statement to avoid this.
Maybe...
unusing namespace xyzzy;
Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this...
namespace codegear {
#include "codegear_header.h"
} // namespace codegear
...then the effects of any using directives within that header are neutralized.
That might be problematic in some cases. That's why every C++ style guide strongly recommends not putting a "using namespace" directive in a header file.
No you can't unuse a namespace. The only thing you can do is putting the using namespace-statement a block to limit it's scope.
Example:
{
using namespace xyzzy;
} // stop using namespace xyzzy here
Maybe you can change the template which is used of your auto-generated headers.
You may be stuck using explicit namespaces on conflicts:
string x; // Doesn't work due to conflicting declarations
::string y; // use the class from the global namespace
std::string z; // use the string class from the std namespace
For future reference : since the XE version there is a new value that you can #define to avoid the dreaded using namespace System; int the include : DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE
How about using sed, perl or some other command-line tool as part of your build process to modify the generated headers after they are generated but before they are used?
Quick experiment with Visual Studio 2005 shows that you can enclose those headers in your own named namespace and then use what you need from this namespace (but don't use the whole namespace, as it will introduces the namespace you want to hide.
#include<iostream>
#include<stdio.h>
namespace namespace1 {
int t = 10;
}
namespace namespace2 {
int t = 20;
}
int main() {
using namespace namespace1;
printf("%d" , t);
printf("%d" , namespace2::t);
}
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.
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!!
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.
In c++ Is it OK to include same namespace twice?
compiler wont give any error but still will it affect in anyway
Thanks,
EDIT:
I meant
using namespace std;
// . . STUFF
using namespace std;
It depends what you mean by 'include'. Saying:
using namespace std;
...
using namespace std:
is OK. But saying:
namespace X {
...
namespace X {
would create a nested namespace called X::X, which is probably not what you wanted.
This usage is fine, if it's what your talking about:
File: foo.h
namespace tools
{
class Widget
{
...
};
}
file: bar.h
namespace tools
{
class Gizmo
{
...
};
}
Twice in the same class/file? It shouldn't be a problem, but neither should it be necessary. I'd naively assume that you should be able to refactor your code to avoid the issue.
Are you asking whether following is okay ?
using namespace std;
using namespace std;
It is okay but normally I prefer to refer the namespace element with scope resolution.
ex:
std::vector
std::sort
I'm not entirely sure what you mean. You can put multiple classes in a single namespace (that's the whole idea). Each class generally has it's own files, so yes, you can use the same namespace in multiple files.
Though not technically required, it's a good idea to have a directory structure that represents the namespace hierarchy you create.
As for for the using directive: the compiler and/or intellisense most likely gives you a warning (the C# one does), but otherwise there is no effect.