C中有const吗?

2022-01-23 00:00:00 c language-comparisons constants c++

这个问题可能很幼稚,但是:

This question may be naive, but:

  • C 中有 const 关键字吗?
  • 从哪个版本开始?
  • C 和 C++ 中的 const 之间是否存在语义和/或句法差异?
  • is there const keyword in C?
  • since which version?
  • are there any semantic and/or syntactic differences between const in C and C++?

推荐答案

关于 const 关键字,C 和 C++ 之间没有语法差异,除了一个相当晦涩的区别:在 C 中(C99 起) 你可以将函数参数声明为

There are no syntactic differences between C and C++ with regard to const keyword, besides a rather obscure one: in C (since C99) you can declare function parameters as

void foo(int a[const]);

相当于

void foo(int *const a);

声明.C++ 不支持这种语法.

declaration. C++ does not support such syntax.

也存在语义差异.正如@Ben Voigt 已经指出的那样,在 C 中 const 声明不会产生常量表达式,即在 C 中,您不能在 case<中使用 const int 对象/code> 标签,作为位域宽度或非 VLA 数组声明中的数组大小(所有这些在 C++ 中都是可能的).此外,const 对象在 C 中默认具有外部链接(C++ 中为内部链接).

Semantic differences exist as well. As @Ben Voigt already noted, in C const declarations do not produce constant expressions, i.e. in C you can't use a const int object in a case label, as a bit-field width or as array size in a non-VLA array declaration (all this is possible in C++). Also, const objects have external linkage by default in C (internal linkage in C++).

至少还有一个语义差异,Ben 没有提到.C++语言的const-正确性规则支持以下标准转换

There's at least one more semantic difference, which Ben did not mention. Const-correctness rules of C++ language support the following standard conversion

int **pp = 0;
const int *const *cpp = pp; // OK in C++

int ***ppp = 0;
int *const *const *cppp = ppp; // OK in C++

这些初始化在 C 中是非法的.

These initializations are illegal in C.

int **pp = 0;
const int *const *cpp = pp; /* ERROR in C */

int ***ppp = 0;
int *const *const *cppp = ppp; /* ERROR in C */

通常,在处理多级指针时,C++ 表示可以在任何间接深度添加 const-qualification,只要您还一直添加 const-qualification 到顶层即可.

Generally, when dealing with multi-level pointers, C++ says that you can add const-qualification at any depth of indirection, as long as you also add const-qualification all the way to the top level.

在 C 中,您只能将 const 限定添加到顶级指针指向的类型,但不能更深.

In C you can only add const-qualification to the type pointed by the top-level pointer, but no deeper.

int **pp = 0;
int *const *cpp = pp; /* OK in C */

int ***ppp = 0;
int **const *cppp = ppp; /* OK in C */

同样的基本一般原则的另一种表现形式是 const 正确性规则在 C 和 C++ 中处理数组的方式.在 C++ 中你可以这样做

Another manifestation of the same underlying general principle is the way const-correctness rules work with arrays in C and C++. In C++ you can do

int a[10];
const int (*p)[10] = &a; // OK in C++

尝试在 C 中做同样的事情会导致错误

Trying to do the same in C will result in an error

int a[10];
const int (*p)[10] = &a; /* ERROR in C */

相关文章