const int x = 42;
or as
#define x 42
The first method is preferable because it ensures type-checking and has other advantages. The second method is a preprocessor macro and does not have type-checking.
Declare a pointer to a constant variable.
This can be done as
const int *px = &x;
This means that the value of *px
cannot be changed, but px
itself can be assigned to point to a different constant variable.
Declare a constant pointer to a variable.
This can be done as
int y;
int *const py = &y;
This means that py
always points to y
, but the value of y
can be changed through py
.
Declare a constant pointer to a constant variable.
This can be done as
const int *const pxy = &x;
This means that both the value of *pxy
and pxy
itself cannot be changed.
const int X=1; or
int const X=1;
这两种形式是完全等效的。后一种方式被认为是不好的风格,不应该使用。
第二行被认为是不好的风格,可能是因为“存储类说明符”(如static和extern)也可以在实际类型之后声明,例如int static等。但是,C委员会(ISO 9899 N1539草案,6.11.5)将此类存储类说明符标记为过时特性。因此,出于统一性考虑,也不应以这种方式编写类型限定符。这只会让读者感到困惑,没有其他用途。
声明指向常量变量的指针。
const int* ptr = &X;
这意味着 'X' 的内容无法被修改。这是声明指针的正常方式,尤其是作为“const正确性”的函数参数的一部分。因为 'X' 实际上不必声明为const,它可以是任何变量。换句话说,您始终可以将变量“升级”为const。从技术上讲,C语言也允许通过显式类型转换从const降级为普通变量,但这样做被认为是不良的编程习惯,并且编译器通常会发出警告。
声明一个常量指针
int* const ptr = &X;
这意味着指针本身是常量。您可以修改它所指向的内容,但不能修改指针本身。这没有太多用途,有一些用途,比如确保在将指向指针(指针指针)作为参数传递给函数时,其地址不会更改。您需要编写类似于以下内容的不太易读的代码:
void func (int*const* ptrptr)
我怀疑许多C程序员无法正确地在其中使用const和*。我知道我做不到 - 我不得不检查GCC。我认为这就是为什么即使它被认为是良好的编程实践,你很少看到指向指针的语法。
常量指针也可以用于确保指针变量本身在只读内存中声明,例如您可能希望声明某种基于指针的查找表并将其分配给NVM。
当然,正如其他回答所示,常量指针也可以用于强制执行“常量正确性”。
声明一个指向常量数据的常量指针
const int* const ptr=&X;
这是上述两种指针类型的结合,具有它们两者的所有属性。
如何声明一个只读成员函数(C++)
既然标记了C++,我应该也提一下你可以将类的成员函数声明为const。这意味着在调用该函数时,不允许修改类的其他成员,这既可以防止类的程序员意外出错,也可以告知调用该成员函数的调用方他们不会因调用它而搞乱任何东西。语法如下:
void MyClass::func (void) const;
const
参数一样的意思。 - David Heffernanconst
正确性保证的必要性。这只是让我们更加确信我们的代码是毋庸置疑的正确的。 - Platinum Azureconst
,因为它们谈到了整体。 - underscore_d