C中的Const数组

san*_*eps 11 c arrays const

原始问题:如果我定义:

const int z[5] = {10, 11, 12, 13, 14}; 
Run Code Online (Sandbox Code Playgroud)

这是不是意味着:

  1. 它是一个常数的整数数组,即z指向的地址总是不变的,永远不会改变,但z的元素可以改变.

要么

  1. z的每个元素都是常量,即它们的值永远不会改变.

编辑:

更多信息:

还有另一个变量:

const int *y = z;
func((int *) y);
Run Code Online (Sandbox Code Playgroud)

其中func定义为:

void func(int y[]) {
    int i;
    for(i = 0; i < 5; i++) {
        y[i] = i; //y[i] can be set to any integer; used i as example
    }
}
Run Code Online (Sandbox Code Playgroud)

在func中,使用y,遍历数组并更改每个元素.即使z的所有元素都是const,这是否有效?

Kei*_*son 15

这意味着每个元素z都是只读的.

z是一个数组,而不是一个指针; 它没有任何意义.与任何对象一样,地址z在其生命周期内不会发生变化.

由于z是一个数组,因此表达式z在大多数但不是所有上下文中都被隐式转换为指向z[0].该地址与整个数组对象的地址一样z,在对象的生命周期内不会发生变化.

要理解数组和指针之间(通常令人困惑的)关系,请阅读comp.lang.c FAQ的第6节.

理解"不变"并且const是两个不同的东西是很重要的.如果某些东西是不变的,那么它会在编译时进行评估; 例如,42并且(2+2)常量表达式.

如果使用const关键字定义对象,则表示它是只读的,而不是(必然)它是常量.这意味着您不能尝试通过其名称修改对象,并尝试通过其他方式修改它(例如,通过将其地址和转换为非const指针)具有未定义的行为.请注意,例如,这个:

const int r = rand();
Run Code Online (Sandbox Code Playgroud)

已验证.r是只读的,但在运行时才能确定其值.

  • C中的`const`对象(不同于C++)不一定是只读的.如果对对象有任何写保护,则留给实现.`const`只是程序员不保证写入对象的保证.编译器可以依赖此合同.还有其他语言,常量和文字之间没有实际区别. (2认同)
  • @simplicisveritatis:如果它已经是一个指针,则不需要“转换”为指针。数组对象包含连续的元素序列。指针对象包含单个地址。它们是完全不同的东西。再次,请阅读 [comp.lang.c FAQ](http://www.c-faq.com) 的第 6 节;它对此的解释比我有时间更详细。 (2认同)

Zie*_*ezi 5

In your case the answer is:

  1. Each element of z is a constant i.e. their value can never change.

You can't create a const array because arrays are objects and can only be created at runtime and const entities are resolved at compile time.

So, the const is interpreted as in the first example below, i.e. applied for the elements of the array. Which means that the following are equivalent: The array in your example needs to be initialized.

 int const z[5] = { /*initial (and only) values*/};
 const int z[5] = { /*-//-*/ };
Run Code Online (Sandbox Code Playgroud)

It is some type commutative property of the const specifier and the type-specifier, in your example int.

Here are few examples to clarify the usage of constant:

1.Constant integers definition: (can not be reassigned). In the below two expression the use of const is equivalent:

int const a = 3;  // after type identifier
const int b = 4;  // equivalent to before type qualifier
Run Code Online (Sandbox Code Playgroud)

2.Constant pointer definition (no pointer arithmetics or reassignment allowed):

int * const p = &anInteger;  // non-constant data, constant pointer
Run Code Online (Sandbox Code Playgroud)

and pointer definition to a constant int (the value of the pointed integer cannot be changed, but the pointer can):

const int *p = &anInteger;  // constant data, non-constant pointer
Run Code Online (Sandbox Code Playgroud)

  • 因为什么时候只能在运行时“创建”数组,在 C 中?如果您将其定义为 const 值数组,那么它将在编译时创建。 (6认同)
  • “`const` 实体在编译时解析”。这是错误的。例如,“const int r = rand();”是有效的,但该值是在运行时计算的 (4认同)