The usage of const in C language

In the C language, const-modified variables have constant attributes, and their values ​​cannot be modified.
E.g:
const int num=10;
int const num=10;
//The value of the variable num cannot be changed

But it has some differences with variables, such as:
#define  line  10
const int num=10;

Although they are both 10 and cannot be changed, they are different when used in arrays. E.g:
int arr[line]
//line is a constant, you can use
int arr[num]
//num is a const-modified variable with constant attributes, which cannot be used in an array here

★When we define the length of the array, we can customize it, which can improve the maintainability of the program. When we want to change the length of the array, just change the declaration directly, instead of changing the value of the variable one by one.

Of course, const can also modify pointers
const int *p;<=>int const *p;
//This statement shows that p is a pointer to a constant, and const modifies the content pointed to by p, so the value it points to cannot be modified, but we can modify the value of the variable p

int *const p ;
//This statement indicates that p is a pointer to an integer constant, the variable p cannot be modified, but the content pointed to by p can be modified

const int *const p;
//This statement indicates that the values ​​pointed to by p and row are modified by const, so this expression cannot be modified in any way

const can also modify the formal parameters of the function, protecting the formal parameters from being modified. E.g:
int  ff(const int x)

Guess you like

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