We all know that,ConstThe usage is very flexible. It is still tricky for new users. It is recommended that you take a look at these two articles. You can refer to this article for a detailed introduction to const usage in C ++ and a detailed description of const usage for C ++ beginners.
Const is unfamiliar and familiar to many people. it can be said that the problem is very difficult to understand in some places. when I first learned C, I had a vague understanding of it. I seem to understand it a little, but I can't say why. I would like to share with you my understanding of it all the time. If you have any mistakes, please advise.
Const can be said to be a constant declaration keyword, such as const int a = 2; variable a is a constant variable, and the value of a cannot be changed, this change cannot be changed in a certain sense. instead, the value cannot be changed directly through the symbol. but in fact, the value of a may change. example:
- #include<stdio.h>
- int main()
- {
- const int a=3;
- int *p=(int*)&a;
- *p=100;
- printf("%d",a);
- return 0;
- }
In this way, the value of a is changed.
Const can also be said to be a read-only keyword, such
- int integerArray[10]={0};
- const int* pointer=integerArray;
Here pointer is a pointer variable pointing to a constant variable. pointer Points to a variable that may change, but the value of the variable it points to cannot be changed directly through pointer. For example:
- *(p+1)=2;
This is not acceptable. But if there is another array, integerArray1, p = integerArray1 can be. There is also a variable pointing to which it cannot be changed. This change is a meaningful change. the following example:
- #include<stdio.h>
- int main()
- {
- int array[10]={0};
- const int *pointer=array;
- int *pointer1=(int*)pointer;
- pointer1[0]=1;
- printf("%d",array[0]);
- return 0;
- }
The above example shows that the array cannot be changed directly through pointer, but the array may be changed indirectly through pointer;
Now let's talk about the const declaration of a constant pointer. Its declaration is not like the declaration of a pointer to a constant. its declaration form is: int * const pointer ;. the point of a regular pointer in programming cannot be changed. therefore, the constant pointer must assign an initial value to it during declaration.
Otherwise, you cannot assign a value to it directly. However, if you must assign a value to it, it is acceptable. The following example:
- #include<stdio.h>
- int main()
- {
- int a=2;
- int* const p;
- int **p1=(int**)&p;
- *p1=&a;
- printf("%d",*p);
- return 0;
- }
After the above introduction, I believe that it is not difficult to write a statement on the constant pointer to a constant. its declaration form: cont int * const p; it is not used for too much introduction. A constant pointer to a constant is a combination of a pointer to a constant and a constant pointer.