In C the const
qualifier makes an object read-only but not a constant expression. For example, it is not possible to use a const int
variable to dimension an array:
const int n = 10;
int arr [n]; /* Compile-time error */
Which is the technical reason for this? Is it not possible for the compiler at compile-time to know that the object has actually a constant value?
I don't think that my question is an exact duplicate of Can a const variable be used to declare the size of an array in C? because I'm not asking if that's possible (it is clearly stated in my question that it is not) but the technical reason why it's not possible.
After the comment of Olaf below, this answer and some musings I would try to summarize and answer my question in this way:
In C a const
object is not a compile-time constant because it can violate both requirements:
First, it is possible to initialize the const
object at runtime as in:
int i;
scanf ("%d", & i);
const int n = i;
so here we violate the requirement of "known at compile-time".
Secondly, as Olaf pointed out, the const
qualifier means that the program itself will not modify the value of the object after the declaration-initialization. But the value of the object in memory could still be modified by some other entity outside the program itself, so here we are not guaranteeing the requirement of actual constness.
Please criticize if this answer is incorrect or incomplete.