Const keyword
Const = read only, which is modified as a read-only variable rather than a constant. The variable modified by const cannot be used as the dimension of the array or placed after case: of the switch statement.
Main functions: 1. By modifying variables or parameters that do not want to be modified with const, the compiler will protect these variables from being modified to enhance system reliability; 2. Enhance code readability
[HTML]View plaincopyprint?
- Const int A; // A is a constant and cannot be modified.
- Int const A; // A is a constant and cannot be modified.
- Const int * A; // A is a pointer to a constant. The value of A can be variable.
- Int * const A; // const modifies a. A is a pointer constant pointing to an integer variable.
Initialization and assignment are required for definition. Once defined, the assignment cannot be modified. When the above Code 1, 2, and 4 are compiled, an error is reported indicating that the Code is not initialized.
If the const and volatile keywords follow the type specifiers, they act on the type specifiers; otherwise, they act on the pointer asterisks next to their left.
The difference between typedef and define lies in two aspects: 1. Define can extend the defined macro type name, while typedef cannot.
[CPP]View plaincopyprint?
- # Define peach int
- Unsigned Peach I; // No problem
- Typedef int Peach;
- Unsiged Peach I; // error, invalid
The define keyword is only a simple replacement of characters, while typedef can be regarded as an encapsulation of types and a new name is given for existing types.
2. In the declaration of several consecutive variables, only typedef can ensure type consistency.
[CPP]View plaincopyprint?
- # Define int_ptr int *;
- Int_ptr chalk, cheese;
Chalk is of the int * type, while cheese is of the int type. Because define is just a simple string replacement
Special usage of typedef
Used to declare function pointers
[HTML]View plaincopyprint?
- Typedef void (* ptr_fun) (INT );
- // Ptr_fun is a function pointer with the int type and the return value is void.
- Ptr_fun Sinal (INT, ptr_fun)
- // Sinal is a function that accepts two types of parameters: int and ptr_fun. The returned value is ptr_fun.
Typedef int A [5];
// A is an array pointer pointing to an integer array with five elements. A represents the (INT) [5] type. That is, a B = {1, 2, 3, 4, 5 };
Const, typedef, define Summary