c++scope-resolution-operator

Why would you write :: with no preceding namespace? (e.g. ::atof)


If you go to the accepted answer of this post

Could someone please elaborate on why he uses:

double temp = ::atof(num.c_str());

and not simply

double temp = atof(num.c_str());

Also, is it considered a good practice to use that syntax when you use "pure" global functions?


Solution

  • It says use the global version, not one declared in local scope. So if someone's declared an atof in your class, this'll be sure to use the global one.

    Have a look at Wikipedia on this subject:

    #include <iostream>
    
    using namespace std;
    
    int n = 12;   // A global variable
    
    int main() {
        int n = 13;   // A local variable
        cout  << ::n << endl;  // Print the global variable: 12
        cout  << n   << endl;  // Print the local variable: 13
    }