C implementation
# Include <stdio. h> # include <stdlib. h> void swap (int * a, int * B); int main (INT argc, char * argv []) {int A = 1, B = 2; int * P1 = & A, * P2 = & B; printf ("before swap! P1 = [% x], P2 = [% x] \ n ", P1, P2); swap (P1, P2); printf (" after swap! P1 = [% x], P2 = [% x] \ n ", P1, P2); getch (); Return 0;} void swap (int *, int * B) {int TMP; TMP = * A; * A = * B; * B = TMP; return ;}
Description: after running the command, you will find that the values of P1 and P2 have not changed before and after swap (P1, P2) is called.
C ++ implementation
# Include <stdio. h> # include <stdlib. h> void swap (Int & A, Int & B); int main (INT argc, char * argv []) {int A = 1, B = 2; printf ("before swap! A = [% x], B = [% x] \ n ", & A, & B); swap (a, B); printf (" after swap! A = [% x], B = [% x] \ n ", & A, & B); getchar (); Return 0;} void swap (Int &, int & B) {int TMP; TMP = A; A = B; B = TMP; return ;}
Description: In this function, swap implements operations on the addresses of Two integer variables. In this way, it must be passed by reference. At this time, the value of A and B in SWAp will also be reflected in the main function.
Conclusion: It is actually very simple to say so much. So to prove what?
1. When passing values, the called function will not change its own parameters.
2. During reference transfer, the called function may change the passed parameters and reflect the situation to the main function. If you do not want to change it, you need to add the const before the parameter to control it.