您的位置:首页 > 编程语言 > C语言/C++

c语言交换两个整型变量的值

2020-06-22 04:33 435 查看

c语言定义一个函数,实现交换两个变量的值,需要传递变量的地址(指针),这样能够保证 swap() 函数交换的是两个指针指向的整型数据。如果只是传递变量的话,例如 try_change(), 交换的是在这个函数体内的变量值,对主函数内的变量值没有影响。

#include <stdio.h>
//指针/变量地址 作函数参数
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
//变量作函数参数,无法成功交换
void try_change(int c, int d){
int tmp = c;
c = d;
d = tmp;
}
int main()
{
//交换成功
int a = 5;
int b = 3;
swap(&a,&b);
printf("num of a:%d\n",a);
printf("num of b:%d\n",b);

//交换失败
int c = 5;
int d = 3;
try_change(c,d);
printf("num of c:%d\n",c);
printf("num of d:%d\n",d);

printf("hello world!\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐