C中的const数组 [英] Const arrays in C

查看:51
本文介绍了C中的const数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原始问题:如果我定义:

Original question: If I define:

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

是不是意思:

  1. 这是一个整数常量数组,即z指向的地址始终是常量,并且永远不会更改,但是z的元素可以更改.

OR

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

更多信息:

还有另一个变量:

const int *y = z;
func((int *) y);

其中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
    }
}

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

where in func, using y, the array is traversed and each element is changed. Is this is valid even though all elements of z are const?

推荐答案

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

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

对象 z 是一个数组对象,而不是指针对象;它没有指向任何东西.像任何对象一样, z 的地址在其生存期内不会更改.

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.

由于 object z 是一个数组,因此在大多数(但不是全部)上下文中, expression z 被隐式转换为指向 z [0] 的指针表达式.该地址与整个数组对象 z 的地址一样,在对象的生存期内不会更改.这种转换"是对表达式含义的编译时调整,而不是运行时类型转换.

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.

要了解数组与指针之间的(通常是混乱的)关系,请阅读 comp.lang.c的第6节常见问题解答.

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

重要的是要理解"constant"和 const 是两个不同的东西.如果某些内容是恒定的,则会在编译时进行评估;例如, 42 (2 + 2)常量表达式.

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.

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

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();

有效. r 是只读的,但是直到运行时才能确定其值.

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

这篇关于C中的const数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆