/**---------------------------------------------------------------------
* @brief 验证const 定义的指针作用
* @note 验证结果如下:
* (1) (const int *PointOne) 与 (int const *PointTwo) 为等效定义
* 且不能进行解引用进行值的修改。
* (2) int *const PointThree; 中,所定义的指针变量不能修改,但能通过
* 解引用进行值的修改。
* 注意:要使得此函数正常执行,需将该函数内有error C2166标志的行进行注释
*---------------------------------------------------------------------*/
int const_point_explain()
{
/*1. 定义变量*/
int VariableOne = 1;
int VariableTwo = 2;
int VariableThree = 3;
int VariableFour = 4;
/*2. 定义指针*/
const int *PointOne = &VariableOne;
int const *PointTwo = &VariableTwo;
int *const PointThree = &VariableThree;
/*3. 指针解引用更改其指向的变量值*/
*PointOne = 5; // error C2166: l-value specifies const object
*PointTwo = 5; // error C2166: l-value specifies const object
*PointThree = 5;
/*4. 修改指针变量值*/
PointOne = &VariableFour;
PointTwo = &VariableFour;
PointThree = &VariableFour; // error C2166: l-value specifies const object
/*5. 打印指针解引用的值*/
printf("Print pointer to:\n");
printf("\t*PointOne = %d\n",*PointOne);
printf("\t*PointTwo = %d\n",*PointTwo);
printf("\t*PointThree = %d\n\n",*PointThree);
/*6. 打印变量值*/
printf("Print the value of the variable:\n");
printf("\tVariableOne = %d\n",VariableOne);
printf("\tVariableOne = %d\n",VariableTwo);
printf("\tVariableOne = %d\n",VariableThree);
return 0;
}
const 定义的指针识别方法:
const 定义的指针识别方法的参考点是'*'这个符号的位置,比如'*'符号位置与指针变量靠在一起,
如果const int *PointOne、int const *PointTwo,则说明*PointOne、*PointTwo是不能更改的。
那么这两个的意思就是解引用的意思,也就是说,*PointOne、*PointTwo不能被赋值,是为只读的。
如果int *const PointThree,'*'这个符号不是和指针变量靠在一起,则说明PointThree是不能被赋值的,
但是*PointThree是可以被赋值的。
总结有以下两点:
(1) '*' 与指针变量靠在一起: *p(解引用的值) 不可改变, 但p(指针变量)可改变。
(2) '*' 不与指针变量靠在一起: *p(解引用的值) 可改变, 但p(指针变量)不可改变。
const 定义的指针变量详解
猜你喜欢
转载自blog.csdn.net/my___sunshine/article/details/104041483
今日推荐
周排行