const keyword | C language

Definition of const

Any variable declaration can be qualified with the const qualifier. This qualifier specifies that the value of the variable cannot be modified. For arrays, the const qualifier specifies that the values ​​of all elements of the array cannot be modified.

E.g:

const double e = 2.71828182845905;
const char msg[] = "warning: ";

e = 3.14;       // 非法
msg[0] = 'a';   // 非法

Const is also often used to modify pointers, indicating that the contents of the pointed area cannot be modified, for example:

int arr[10] = {0};
const int* p_arr = arr;

arr[0] = 1;         // 合法
p_arr[0] = 1;       // 非法

Constant pointers and pointer constants

Constant pointer, indicating that the variable is a pointer, points to a constant, that is, the memory area pointed to by the pointer cannot be modified.

int arr[10] = {0};
int arr_2[10] = {0};
const int* p_arr = arr;     // 声明常量指针

arr[0] = 1;         // 合法
p_arr[0] = 1;       // 非法
p_arr = arr_2;      // 合法

Pointer constant, indicating that the variable is a constant, and the value of the variable itself cannot be modified.

int arr[10] = {0};
int arr_2[10] = {0};
int * const  p_arr = arr;     // 声明指针常量

arr[0] = 1;         // 合法
p_arr[0] = 1;       // 合法
p_arr = arr_2;      // 非法

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325505992&siteId=291194637