用c语言编写交换两个变量的值的函数,函数参数分别使用原变量、指针变量、引用变量,在主函数调用这三个不同的函数,观察其运行结果的不同。
时间: 2024-09-19 12:02:46 浏览: 89
在C语言中,我们可以编写三个不同的函数来交换两个变量的值,分别是直接通过参数传递、通过指针以及通过引用。这里是一个简单的示例:
1. **通过参数传递** (非指针)
```c
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x=%d, y=%d\n", x, y);
swap(x, y);
printf("After swap by passing: x=%d, y=%d\n", x, y);
return 0;
}
```
2. **通过指针**:
```c
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x=%d, y=%d\n", x, y);
swap(&x, &y);
printf("After swap by pointer: x=%d, y=%d\n", x, y);
return 0;
}
```
3. **通过引用** (C++中可用,C中无此语法):
```cpp
// 如果是C++
#include <iostream>
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
std::cout << "Before swap: x=" << x << ", y=" << y << std::endl;
swap(x, y);
std::cout << "After swap by reference: x=" << x << ", y=" << y << std::endl;
return 0;
}
```
阅读全文