Why in C a const object is not a compile-time constant expression? [duplicate]

拟墨画扇 提交于 2019-12-11 08:02:24

问题


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.


回答1:


One technical reason for this is probably that such a declaration is even valid when the initializer is not a constant expression, so this is a semantic property that is deduced from looking at the initializer.

Then, with the current rules there is no way to have such a thing in a header file to be declared and defined in file scope. Any object can only have one definition, and several object files could not be linked together.

There are ideas to improve that situation for the next version of C.



来源:https://stackoverflow.com/questions/40062767/why-in-c-a-const-object-is-not-a-compile-time-constant-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!