<> subject : Use function to implement two numbers of code
<> Conventional thinking :
Defining functions , Call function , Complete the exchange .
Is your code the same as below ?
#include<stdio.h> #include<stdlib.h> void Swap(int a,int b) { int tmp = a; a =
b; b = tmp; } int main() { int x = 10; int y = 20; Swap(x,y); printf("%d %d\n",
x, y); system("pause"); return 0; }
If your code is the same as above , Congratulations , Fall into the pit successfully .
Why? ? At this time, we have to break the conventional thinking , Because it involves actual parameters and formal parameters .
<> be careful :
Parameters in defining functions are called formal parameters ( Formal parameter ) The parameters in the calling function are called arguments ( Actual parameters )
The formal parameter of a function is a copy of the argument ( copy ), In the code above , Just exchange the parameters in the definition function , Copy only ( Shape parameter ) Exchange does not, of course, implement arguments ( The variables we actually want to exchange ) Exchange of . in other words : We're just exchanging a and b Value of , Not really x and y Exchange , What we really want to exchange is a and b Value of .
At this time, we need to use the method of passing the pointer to modify the variables outside the function . Conversion of pointer type to formal parameter , It is equivalent to connecting two unrelated parameters , Here are the specific codes ( For reference only )
#include<stdio.h> #include<stdlib.h> void Swap(int* a,int* b) { int tmp = *a; *
a= *b; *b = tmp; } int main() { int x = 10; int y = 20; // be careful , The parameter passed here is the address Swap(&x,&
y); printf("%d %d\n", x, y); system("pause"); return 0; }
It's the address , You can also pass process parameters by passing references
<> experience :
It's a little difficult to understand for the first time , This should be one of the more difficult functions , But if I go to see it the second time , It's much easier to understand , Growing up through mistakes , Keep trying , come on. !
Technology