0

Usually when someone declares using namespace std; (I know that it is a bad habit), They should declare it like that:

# include <iostream>
using namespace std;

int main()
{
    // Some code here...
    return 0;
}

But it is a completely different story here. The using namespace std; is sometimes located in int main() (Code 1.12), Maybe in a function named Hello (Code 1.13):

Code 1.12

# include <iostream>

int main()
{
    using namespace std;
    // Some code after namespace...
    return 0;
}

Code 1.13

# include <iostream>

void Hello()
{
    using namespace std;
    // Some code again...
}

int main() // Adding up main just to ensure there are no errors
{
    return 0;
}

Why do they need to initialize using namespace std;, in a function or in function main?

  • `using namespace std;` is bad in headers. Thats what is explained in the Q&A you link. Using it elsewhere is fine. Your question is somewhat unclear. Who is "they" ? in your examples the line can be removed without consequences. Its the same as elsewhere, it introduces all names from `std` such that you need to prepend every name with `std::` – 463035818_is_not_an_ai Jul 19 '22 at 11:46
  • No idea, but just remove the using namespace std, and type std:: where needed. Just learn the good habit :) Just NEVER use "using namespace" in a header. – Pepijn Kramer Jul 19 '22 at 11:47
  • I'm with @pepijn. There's a reason why `std` is nice and short :) – Paul Sanders Jul 19 '22 at 12:10
  • You're asking why? Do you know what that line does? Because if you do, that's why. – sweenish Jul 19 '22 at 12:55
  • It would be best if you stop doing `using namespace std;` in any case. Many coding standards forbids that. – Marek R Jul 19 '22 at 14:46

1 Answers1

3

The using for namespaces statement pulls in all symbols from the namespace into the current scope.

If you do it in the global namespace scope then all symbols from the std namespace would be available in the global (::) namespace. But only for the current translation unit.

If you do using inside the function, or even a nested block inside a function, then the symbols from std would only be pulled into that (more narrow) scope.


Lets take your last example, and add some stuff to it:

#include <iostream>

void Hello()
{
    using namespace std;
    cout << "Hello\n";  // Valid, cout is in the current scope
}

int main()
{
    cout << "World\n";  // Not valid, there's no cout symbol in the current scope
}

Here cout is available only inside the Hello function, because that's where you added std::cout to the functions scope.

In the main function there's no such symbol cout.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621