Search code examples
c++constantsglobalredeclaration

C++ allows redefinition of global (const) variable?


I'm a bit confused by global constants. My (beginner level) understanding is that 'global' variables are defined outside of a block and have program scope (source: http://www.learncpp.com/cpp-tutorial/42-global-variables/). But the program:

#include <iostream>

const double x=1.5;

int main(){
        std::cout << "1) x=" << x << std::endl;
        double x=2.5;
        std::cout << "2) x=" << x << std::endl;
        //const double x=3.5;
        return 0;
}

compiles in g++ (GCC, latest 64-bit version) without any problems, even with -Wall.

The output:

1) x=1.5
2) x=2.5

This is confusing to me. The fact that the first cout evaluates means that main recognises 'x' as a 'global' variable (it wasn't defined in main's scope). If that is the case, why does it let me redefine 'x'?

Then, if you uncomment the commented third declaration, g++ throws up a redeclaration error. Meaning, my first declaration can't have been 'global', in the sense I defined :S

edit: okay, question has nothing to do with global variables, but scopes: e.g same problem in http://pastebin.com/raw.php?i=V5xni19M


Solution

  • #include <iostream>
    
    const double x=1.5;
    

    At this point in code, there is one object named x in the global scope, and it is of type const double.

    int main(){
            std::cout << "1) x=" << x << std::endl;
    

    At this point, there's still just one x visible (the global one), so that's what the name x refers to.

            double x=2.5;
    

    At this point in code, you've introduced an object named x into the scope of main(). That scope is nested inside global scope, so now you have two objects named x:

    1. x in global scope of type const double

    2. x in the scope of main() of type double

    The local x hides the global x. If you want to access the global x inside main(), you can refer to it as ::x.

        std::cout << "2) x=" << x << std::endl;
        double x=3.5;  //uncommented
    

    No you're trying to introduce another object named x into the scope of main(). This is not possible, there already is one x in that scope, so it fails.