const use
Declare a constant
The keyword const is used to tell the compiler that a variable once initialized cannot be modified
int a;
const int n;
A constant pointer
Pointer to a constant
Modified pointer points to
#include<stdio.h>
int main() {
//常量指针
const int num = 10;
// num = 100;
int* p1 = #
*p1 = 100;
printf("%d\n", num); // 可以通过p1修改num (c语言可以c++不可以)
// 不可以通过p2,p3修改num
const int* p2 = #
//*p2 = 100;
printf("%d\n", num);
int const* p3 = #
//*p3 = 100;
printf("%d\n", num);
return 0;
}
// 不能通过指针修改指向的内容(必须初始化变量)
// 可以改变指针指向
Two pointer constant
The pointer itself is a constant
Decorate the pointer itself
// 指针常量:
int a = 0;
int* const pa = &a;
// pa = NULL;
*pa = 100;
// 可以通过指针修改指向的内容
// 不能改变指针指向(必须初始化指针)
Three constant pointer constants
The pointer itself is a constant and points to a constant
Simultaneous modification
// 常量指针常量
const int b = 0;
const int * const pb = &b;
// pb = NULL;
// *pb = 0;
// 不能通过指针修改指向的内容(必须初始化变量)
// 不能改变指针指向(必须初始化指针)