Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to put using namespace std;

I'm wondering where to put using namespace std;. I saw a code with the using namespace std; in the int main(){} but I was putting it after #include <iostream>. Where should I put it and does it make any difference where I put it?

like image 613
Hikari Iwasaki Avatar asked Jun 24 '11 23:06

Hikari Iwasaki


2 Answers

Adding it inside of a function restricts the scope of the using statement to that function only. You should never put a using statement inside of a header as to avoid conflicts for users of your header file(s).

Putting it above main in the file scope is fine if you know that no conflicts will arise, but even that may cause problems with other imported types and is generally to be avoided in moderately sized projects. I try to avoid pollution of the global namespace as much as possible, but if I am writing a one-off, small implementation file I will add a using namespace std; at the top for convenience.

In your case, assuming you only want to use std::cout and std::cin (just an example), you can do this:

using std::cout;
using std::cin;

Now you can write cin >> whatever and cout << whatever without fully qualifying the type/object each time and you also avoid polluting the global namespace.

like image 103
Ed S. Avatar answered Sep 17 '22 20:09

Ed S.


It makes a huge difference where you put it.

If you put it inside a function, then it only applies in that function.

If you put it outside a function in global scope then it applies to everything after that point.

If you put it outside a function in global scope in a header file then it will even apply to ever file that includes that header.

Generally, it's very bad practice to use it at global scope in a header, and semi bad practice to use it in global scope at all since in Unity builds, the distinction between headers and source files is blurred.

You would be best to just use it in the functions that you need it, or even not use it at all and just prefix standard library functions/classes with std::.

like image 41
Peter Alexander Avatar answered Sep 18 '22 20:09

Peter Alexander