Function to exchange two numbers
First of all, let's see if we can't use functions, how can we exchange two numbers?
#include <stdio.h>
int main()
{
int a = 50;
int b = 100;
int temp = a;
a = b;
b = temp;
printf("a=%d b=%d\n", a, b);
system("pause");
return 0;
}
Result: a and b successfully realized the exchange.
So how to use the function?
Many people think that just put the part of the above exchange numbers into the function, then let's try:
#include <stdio.h>
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}
int main()
{
int a = 50;
int b = 100;
swap(a, b);
printf("a=%d b=%d\n", a, b);
system("pause");
return 0;
}
result:
Analysis: We can see that in this code, there is no exchange between a and b.
So did x and y swap?
We can add code to output x and y values in the function to take a look.
Code:
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
printf("x=%d y=%d\n", x, y);
}
Result:
Analysis: In this code, we found that a and b did not exchange. What is exchanged inside the function is x and y, x and y are equivalent to new local variables created, but initialized by a and b. Exchanging x and y does not affect a and b.
The reason is: x and y accessed inside the function are not the ontology of a and b .
To solve this problem, you need to find a way to make the variables outside the function accessible inside the function. In C language, we cannot directly access local variables outside the function, but we can use pointers to indirectly access external variables .
Code:
void swap(int* x, int* y){
int temp = *x;
*x = *y;
*y = temp;
}
The swap function here is equivalent to the following code:
int* x = &a;
int* y = &b;
int temp = *x;
*x = *y;
*y = temp;
int temp = a;
a = b;
b = temp;
printf("a = %d, b = %d\n", a, b);
In this code, first define two pointer variables x and y, where x holds the address of a and y holds the address of b. Represents the dereference of the pointer and indicates the target pointed to by the pointer. So x is equivalent to a, *y is equivalent to, and then exchange a, b through the temporary variable temp.
The final code implementation:
#include <stdio.h>
void swap(int* x, int* y){
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 50;
int b = 100;
swap(&a, &b);
printf("a=%d b=%d\n", a, b);
system("pause");
return 0;
}