C language constant pointer and pointer to constant object | C language

Before discussing constant pointers and pointers to constant objects, we must first clarify what a pointer is

pointer

A pointer is a reference to a data object or function; a
pointer represents the address and type of an object or function ; the
declared pointer (name) is also an object .

int var = 8848;
int* ptr = &var;

ptr is an int pointer to the variable var

Constant pointers and pointers to constant objects

Constant pointer When
defining a constant pointer, the pointer must be initialized because its value cannot be modified later.

int var = 8848;
int var_c = 8086;
int* const ptr = &var;

*ptr = 1024;	//OK
ptr = &var_c;	// Error: assignment of read-only variable 'ptr'. 
// prt被const修饰,是一个常量指针,是只读的 

The const in the third line is followed by the pointer ptr. This const modifies the object of ptr, saying that ptr is a constant pointer.
Pointer to constant object

int var = 8848;
int var_c = 8086;
int const * ptr;	// 与下一行是等价的
const int* ptr;		// 与上一行是等价的

ptr = &var_c;	// OK
*ptr = 1024;	// Error

The const modifier in the above example is *ptr, so *prt is read-only. But ptr is a pointer object, and ptr is not a constant.

summary

Constant pointer (a constant pointer to an object), emphasizing that the pointer itself is a constant.
Pointer to a constant object, emphasizing that the object pointed to by the pointer is a constant.
Of course, there are also constant pointers to constant objects (const int* const prt = &var;)

Guess you like

Origin blog.csdn.net/qq_40759015/article/details/114363274