有常量用C? [英] Is there const in C?

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

问题描述

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

This question may be naive, but:


  • 用C常量关键字?

  • 自哪个版本?

  • 有没有在C和C ++ 常量之间的任何语义和/或语法上的不同?

  • is there const keyword in C?
  • since which version?
  • are there any semantic and/or syntactic differences between const in C and C++?

推荐答案

有关于C和C ++之间没有语法上的不同,以常量关键字,除了一个相当不起眼的1 :在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福格特已经指出的那样,在C 常量声明不会产生恒定的前pressions,即c您不能使用常量INT 对象在情况标签,作为一个位字段宽度或在非VLA数组声明数组的大小(这一切都是可能的C ++)。此外,常量对象都默认用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++).

有至少有一个更多的语义差异,这本没有提及。的C ++语言支持常量,正确性规则以下标准转换

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的资格,只要你还添加const的资格一路到顶层。

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语言中只能添加常量资格由顶级指针所指向的类型,但没有更深。

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 */

的相同的底层一般原则另一个表现是这样的常量,正确性规则,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 */

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

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