What is the role of const in q9:c++?
(1) const is used to define constants: const-defined constants compilers can perform data-static security checks on them.
(2) The formal parameters of the const modifier function:
A. If the input parameter is "pointer passing", then the const modifier prevents accidental changes to the pointer, which can be used as a protective function.
The usage of the const & modifier input parameter is summarized as follows:
A. For input parameters of non-internal data types, the "value passing" method should be changed to "const reference passing" to improve efficiency. For example, void Func (a a) is changed to void func (const a &a).
B. For input parameters of the internal data type, do not change the "value passing" method to "Const reference pass". Otherwise, it can not achieve the purpose of improving efficiency, but also reduces the comprehensible function. For example void Func (int x)
B. If the input parameter is "pointer passing", then the const modifier prevents accidental changes to the pointer, which can be used as a protective function.
The definition of a const pointer:
A const pointer is a pointer variable when the value is initialized, it cannot be changed to point to, initialization is necessary. The form is defined as follows:
Type *const pointer name;
When you declare a pointer, you can use the keyword const before or after the type, or you can use it in two locations. For example, the following are legal declarations, but the meanings are very different:
const int * PONE; A pointer to an integer constant that points to a value that cannot be modified
int * Const PTWO; A constant pointer to an integer that cannot point to another variable, but the value that points to (the variable) can be modified.
const int *const pthree; A constant pointer to an integer constant. It can no longer point to another constant, and the value pointed to cannot be modified.
The trick to understanding these declarations is to look at the right side of the keyword const to determine what is declared as a constant, and if the right side of the keyword is a type, the value is a constant, and if the right side of the keyword is a pointer variable, the pointer itself is a constant. The following code helps illustrate this point:
const int *P1; The int pointed to IS constant
int * const P2; P2 is constant, it can ' t point to anything else
C and C + + programmer interview Cheats