consider following array declaration:
int const a[5]; from semantic standpoint of language, equivalent const int a[5]? assuming case, both declarations read "a array of 5 constant ints".
the alternative way read first declaration "a constant array of 5 ints".
obviously, both of statements logically imply whole array constant; if array consists of 5 constant ints, entire array constant. alternatively, if whole array constant, of values constant.
i aware notion of "constant array" bit meaningless since arrays not modifiable lvalues (that is, cannot appear on left side of assignment). however, there circumstances under these 2 declarations yield different behaviour?
(cdecl.org rejects first declaration syntax error, while current compilers accept it.)
edit:
the linked duplicate asks whether order of const matters ordinary variables. arrays, bit more confusing, don't consider duplicate.
is equivalent
const int a[5]
yes, is.
the alternative way read first declaration "a constant array of 5 ints".
not really. declaration, written, applies const array elements specifically. in order apply const array (as opposed applying array elements), you'd have like
int (const a)[5]; but such declaration syntactically invalid in c.
an indirect attempt apply const array can made through intermediate typedef
typedef int a[5]; const a; but in case, per language rules, const qualifier "falls through" array elements , whole thing equivalent
const int a[5]; note, again, const a; above not immediately equivalent const int a[5];. equivalent aforementioned int (const a)[5]; (!). (it legal way sneak int (const a)[5]; past compiler's defenses.) int (const a)[5]; very-short lived - gets transformed const int a[5]; compiler.
if array consists of 5 constant ints, entire array constant. alternatively, if whole array constant, of values constant.
well, not entirely true. c language differentiate between array object , elements. conceptually, these different entities. example, noted yourself, language spec says arrays non-modifiable lvalues. this, of course, not prevent array elements modifiable.
this conceptual distinction between array whole , individual array elements, combined "fall through" behavior const leads following unpleasant situation
typedef int a[5]; a; const *p = &a; // error!!! i.e. breaks "normal" const-correctness rule allows initialize const t * pointers t * values. (c++ deliberately updated const-correctness rules make above code behave "as expected", c insists on rejecting it.)
Comments
Post a Comment