Which definitions are the same for several statements? What are the different definitions? What data can be modified? What data is not modifiable?
1 Const int A; 2 int Const A; 3 Const int *A; 4 INT *const A; 5 int Const *const A;
In C + +, const is a data type modifier, as well as short, long, unsigned, static, extern, and so on, defining variables in the following way:
(modifier + data type) variable name
Note: If there are modifiers, the position of the modifier and data type does not affect the definition of the variable, such as the semantics of int short and short int are the same.
Therefore, the const int A is the same as the int const A, which defines a variable of type const int, and the value cannot be modified.
For the understanding of pointer variable types:
First (), [], * the priority of these three symbols is reduced sequentially, so the following two statements have different meanings:
1 int *a[// defines a 10-bit array, each member is a pointer to int 2int (*a) [ten] ; // A pointer is defined that points to an array of 10 int
Also remember that the pointer action is from right to left.
After looking back at the three statements, it's easy to see:
The const int *A indicates that a is a pointer to the const int type, and the data pointed to is not modifiable;
int *const A means that const A is a pointer to an int, the data pointed to can be modified, and the pointer cannot point to another address;
The int const *CONST A indicates that const A is a pointer to a const int, the data pointed to cannot be modified, and the pointer cannot point to a different address.
Attention:
void* VP; Const VP ptr; Const void *ptr;
Is the definition of two ptr the same? The answer is different. typedef defines a new type of data, so the Const VP PTR is the same semantics as the VP Const PTR, so in this sentence ptr is a const type, stored in the code snippet, and the const void *ptr is a normal pointer to the const Data of type void, which can point to somewhere else and stored in the data segment. Therefore, the two statements are stored in a different location.
Why use const?
- Send a message to another programmer: Do not modify this value;
- Is it possible for the compiler to produce streamlined code? Reduce bugs? (I don't quite understand this phrase at the moment)
- Reasonable protection of read-only data;
Use location:
- Define constants to prevent them from being modified;
- function arguments to prevent function modifications as variable values for function arguments
- In C + +, the use of class member functions
Const (2)