Home > OS >  using namespace in c
using namespace in c

Time:11-09

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();
}  

CodePudding user response:

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.

CodePudding user response:

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.

  • Related