Initializing const variable
Can we in开发者_C百科itialize a const variable as follows
int var1 = 10;
const int var2 = var1;
Will this cause any warning/error in any compiler ?
Depends where the code is.
If it's inside a function, so that var1
and var2
are automatics, then yes this is fine. var2
is only initialized by copying var1
anyway, so the fact that var1
can be modified later has no bearing on the fact that var2
can't.
If it's in file scope, so that var1
and var2
are statics, then no it is not fine. A const integer object at file scope must be initialized with a value certain to be known at compile time (in C++ this is called an "integer constant expression", I forget whether that's the exact C terminology too). In this case, you might think that because there's no code in between the two definitions, the value of var1
would be known at compile time to be 10
, but because the type is non-const, the standard forbids it anyway. You can think of this as being in order to avoid implementations needing to be smart enough to apply that line of reasoning and prove that there's nothing capable of modifying var1
: all it has to look at is the type, not the intervening code.
Yes, it's OK. It's part of C and C++ standards. A constant object can be initialized with a non-const object. Why wouldn't it?
精彩评论