The following program compiles:
template
class Test{};
extern const int var = 42; //extern needed to force external linkage
int main(
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.
}