Combination of C language keyword const and pointer


Let’s first define three variables

1、const int *p1
2、int const *p2
3、int *const p3
The three pointers P1, P2 and P3 all point to int type. What’s the difference between them

Write a code to test it


Compile it


You can see the error reported on lines 11, 12 and 16, from which you can draw the following conclusions:

Const int * has the same effect as int const *. The memory pointed to cannot be changed, that is, the content pointed to by the pointer is read-only, or a constant. However, the pointing position can be changed, that is, P1 and P2 can point to other constants again.

On the contrary, char * const indicates that the content of the pointer is read-only, that is, the position pointed to by the pointer cannot be modified, but the memory pointed to by the pointer is readable and writable.

What if the memory and location pointed to cannot be changed?

Hahaha, I’m sure you can think of it,

Int * const const pointer and const int * const pointer are OK.

What if const and typedef were used together?

//Define a new type first
typedef int *intp;
const intp p1;
intp const p2;

P1 and P2, which pointing position cannot be changed and which pointing memory cannot be changed?

The answer is: P1 and P2 are the same. The pointing position cannot be changed, that is, if you point to a, you can no longer point to B.

Therefore, if the content you want to point to cannot be changed, you can’t use typedef to define a new type.
Here are the validation code and compilation results




The above is the combination of C language keyword const and pointer introduced by Xiaobian. I hope it will be helpful to you!

Recommended Today

Big data Hadoop — spark SQL + spark streaming

catalogue 1、 Spark SQL overview 2、 Sparksql version 1) Evolution of sparksql 2) Comparison between shark and sparksql 3)SparkSession 3、 RDD, dataframes and dataset 1) Relationship between the three 1)RDD 1. Core concept 2. RDD simple operation 3、RDD API 1)Transformation 2)Action 4. Actual operation 2)DataFrames 1. DSL style syntax operation 1) Dataframe creation 2. SQL […]