Const is used to protect program robustness and reduce program risks.
The usage of const is complicated. It can be summarized as follows:
1: used when defining variables:
A: const int a = 100; the simplest usage means that variable a is a constant variable;
B: int const B = 100; same as;
C: const int * a = & B; pointer to a constant, that is, the value of the pointer itself is OK.
Changed, but the content pointed to cannot be changed;
D: int const * a = & B; same function as c;
E: int * const a = & B; constant pointer, that is, the value of the pointer itself cannot be changed,
However, the content to be pointed to can be changed;
F: const int * const a = & B; a constant pointer to a constant, that is, the pointer and
The content to be pointed to cannot be changed;
G: const int & a = 100; constant reference, that is, the reference value cannot be changed;
Conclusion: initialization is required when you use const to define variables.
Mark (*, &) indicates the content to be directed to on the left, and on the right, indicates itself.
2: Used in functions:
A: void func (const int a); used as a parameter, it indicates that the function body is not
This parameter can be modified. For different formats when no parameter is defined, see defining variables.
Usage;
B: const int func (); used as the return value, indicating that the return value of the function is not
If it can be modified, apply const int a = func () when obtaining the return value;
Parameters are defined in different forms. For more information, see How to Use variables;
C: int func () const; a regular function, which indicates that a function cannot modify a member of a class.
Value, which can only be used in member functions of the class;
Conclusion: Using const in a function is similar to defining variables.
The above is a bit of work experience. please correct me if you have any errors! Thank you!