Thread: Namespaces - which function to call?

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    144

    Namespaces - which function to call?

    Hello everyone.

    In the following code, a statement calls function sqrt(), when there are two functions called sqrt(). Is there a rule of "Assume the programmer means the one in the same namespace that we're in", when there's ambiguity? Same for variables, too.

    Code:
    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    namespace mynmspc
    {
    	double sqrt(double x) { cout << "mynmspc::sqrt()\n"; return 42.0; }
    	void fn() { cout << sqrt(3.14); } // Which sqrt()?
    }
    
    int main()
    {
    	mynmspc::fn();
    	return 0;
    }

  2. #2
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    This is probably a fantastic case for not using "using namespace std;" and also calling functions in an unqualified way.

    But to answer your question, because there's multiple suitable definitions of "sqrt" floating around, the compiler will seek out the most immediate best match which happens to be in the same namespace so it will use that.

    Here's a Compiler Explorer link to show you which is called: https://godbolt.org/g/9VKLKF

    The key to nice is that pmr::sqrt is what's called in the resulting assembly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function call Overhead and Function Call Stack
    By Alam Khan in forum C++ Programming
    Replies: 2
    Last Post: 04-26-2014, 08:28 AM
  2. Function Prototype, Function Call, and Function definition
    By dmcarpenter in forum C Programming
    Replies: 9
    Last Post: 04-09-2013, 03:29 AM
  3. Replies: 8
    Last Post: 07-08-2011, 01:16 PM
  4. Replies: 5
    Last Post: 10-17-2006, 08:54 AM
  5. Replies: 2
    Last Post: 06-21-2005, 02:41 PM

Tags for this Thread