问题描述
考虑以下数组声明:
INT常量一个[5];
从语言的语义的角度来看,它是完全等同于 const int的一个[5]
?假设是,双方的声明将基本上阅读等的情况下的 a为常数5的整数数组的。
读取第一个声明将是另一种方式的 a是5整数的一个常量数组。
显然,两个发言的逻辑意味着整个阵列是常数;如果一个数组包含5个整数不变,则整个数组是恒定的。或者,如果整个阵列是恒定的,则其所有值也是常数。
据我所知,一个常量数组的概念是有点意义的,因为数组是不可修改的左值(也就是说,他们不能在赋值的左侧出现)。但是,是否有任何情况下,这两个声明会产生不同的行为?
(拒绝第一个声明为一个语法错误,而目前大多数编译器接受它。)
编辑:
链接的重复询问是否为普通变量常量的顺序
事项。随着阵列,这是更混乱了一点,所以我不认为这是一个重复的。
Yes, it is.
Not really. Your declaration, as written, applies const
to array elements specifically. In order to apply the const
to the array itself (as opposed to applying it to the array elements), you'd have to do something like
int (const a)[5];
but such declaration is syntactically invalid in C.
An indirect attempt to apply const
to the array itself can be made through an intermediate typedef
typedef int A[5];
const A a;
but in this case, per language rules, the const
qualifier "falls through" to array elements and the whole thing is just equivalent to
const int a[5];
Note, again, that const A a;
above is not immediately equivalent to const int a[5];
. It is actually equivalent to the aforementioned int (const a)[5];
(!). (It is a legal way to sneak int (const a)[5];
past compiler's defenses.) But that int (const a)[5];
is very-short lived - it gets immediately transformed into const int a[5];
by the compiler.
Well, that is not entirely true. C language does differentiate between the array object itself and its elements. Conceptually, these are different entities. For example, as you noted yourself, the language spec says that arrays are non-modifiable lvalues. This, of course, does not prevent array elements to be modifiable.
This conceptual distinction between array as a whole and individual array elements, combined with the "fall through" behavior for const
is exactly what leads to the following unpleasant situation
typedef int A[5];
A a;
const A *p = &a; // ERROR!!!
i.e. it breaks the "normal" const-correctness rule that allows us to initialize const T *
pointers with T *
values. (C++ deliberately updated it const-correctness rules to make the above code to behave "as expected", but C insists on rejecting it.)
这篇关于什么`INT常量一个[5]`究竟意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!