Why can't a constant pointer be a constant expression?

后端 未结 3 782
南旧
南旧 2020-12-29 03:11

The following program compiles:

template 
class Test{};

extern const int var = 42; //extern needed to force external linkage

int main(         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 03:18

    The problem is because your C++ program can be loaded at any point in memory, and so the address of a global var may be different each time you run the program. What happens if you run your program twice? var is obviously in two different locations then.

    Even worse, in your example, you take the address of a variable on the stack! look at this:

    void myfunction( unsigned int depth) {
         const int myvar = depth;
         const int * const myptr = &myvar;
         if (depth)
             myfunction(depth-1);
    }
    

    If main calls myfunction(3), then 3 myvars are created at seperate locations. There's no way for the compile time to even know how many myvars are created, much less there exact locations.

    Finally: declaring a variable to be const means: "I promise", and does not mean that is a compile time constant. See this example:

    int main(int argc, char** argv) {
        const int cargc = argc;
        char* myargs[cargc]; //the size is constant, but not a _compile time_ constant.
    }
    

提交回复
热议问题