The non-pointer parameter (that is, the value passing parameter) will not be modified to the original value. Const has no meaning for it.
Const is only used for pointers.
1. First usage: const type * variable:
This method limits the modification of the pointer to the value.
# Include <stdio. h> int fun (const int * P) {* P + = 1;/* execute */return * P;} int main (void) only when the const is removed) {int num = 3; printf ("% d \ n", fun (& num); getchar (); Return 0 ;}
2. However, you can bypass this restriction:
# Include <stdio. h> int fun (const int * P) {int * P2 = P;/* a duplicate pointer bypasses the const limit */* P2 + = 1; return * P;} int main (void) {int num = 3; printf ("% d \ n", fun (& num )); /* 4 */getchar (); Return 0 ;}
2. Second usage: type * const variable:
This method limits pointer pointing. The following example attempts to modify the pointer and will not succeed.
# Include <stdio. h> void swap (int * const P1, int * const P2) {int * t = p1; P2 = p1; P2 = T;} int main (void) {int x = 111; int y = 222; printf ("% d, % d \ n", x, y); swap (& X, & Y ); printf ("% d, % d \ n", x, y); getchar (); Return 0 ;}
3. In fact, * const is not used, and the pointer will not be modified:
In the above example, removing the const... function won't be successful.
Why? Because the pointer itself acts as a parameter, it is only a copy (but the value pointed to by the copy is true ).
# Include <stdio. h> void swap (int * P1, int * P2) {int * t = p1; P2 = p1; P2 = T;} int main (void) {int x = 111; int y = 222; printf ("% d, % d \ n", x, y); swap (& X, & Y); printf ("% d, % d \ n ", x, y); getchar (); Return 0 ;}
4. But the second method does not modify the value pointed to by the pointer:
This can also ultimately complete the swap function; in terms of this function itself, it is completely possible to not use Const.
# Include <stdio. h> void swap (int * const P1, int * const P2) {int T = * P1; * P1 = * P2; * P2 = T;} int main (void) {int x = 111; int y = 222; printf ("% d, % d \ n", x, y); swap (& X, & Y ); printf ("% d, % d \ n", x, y); getchar (); Return 0 ;}
5. Two methods can even be used together:
# Include <stdio. h> int fun (INT const * const P1, int const * const P2) {return * P1 + * P2;} int main (void) {int x = 111; int y = 222; printf ("% d \ n", fun (& X, & Y); getchar (); Return 0 ;}