Const arrays in C

后端 未结 2 668
长情又很酷
长情又很酷 2021-02-18 14:42

Original question: If I define:

const int z[5] = {10, 11, 12, 13, 14}; 

does it mean:

  1. it\'s a constant array of integers i.e. the
2条回答
  •  长情又很酷
    2021-02-18 15:29

    It means that each element of z is read-only.

    The object z is an array object, not a pointer object; it doesn't point to anything. Like any object, the address of z does not change during its lifetime.

    Since the object z is an array, the expression z, in most but not all contexts, is implicitly converted to a pointer expression, pointing to z[0]. That address, like the address of the entire array object z, doesn't change during the object's lifetime. This "conversion" is a compile-time adjustment to the meaning of the expression, not a run-time type conversion.

    To understand the (often confusing) relationship between arrays and pointers, read section 6 of the comp.lang.c FAQ.

    It's important to understand that "constant" and const are two different things. If something is constant, it's evaluated at compile time; for example, 42 and (2+2) are constant expressions.

    If an object is defined with the const keyword, that means that it's read-only, not (necessarily) that it's constant. It means that you can't attempt to modify the object via its name, and attempting to modify it by other means (say, by taking its address and casting to a non-const pointer) has undefined behavior. Note, for example, that this:

    const int r = rand();
    

    is valid. r is read-only, but its value cannot be determined until run time.

提交回复
热议问题