码迷,mamicode.com
首页 > 其他好文 > 详细

1交换

时间:2017-04-27 00:32:38      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:地址   stdio.h   efi   int   iostream   按值传递   实参   pause   style   

#include "swap.h"
#include <stdio.h>
#include <iostream>

using namespace std;
#define swap_m(x,y,t) ((t)=(x),(x)=(y),(y)=(t))        // #define后面不要加 分号;
void swap(int x,int y);
void swap_p(int *px,int *py);

int main()
{
    int a,b,temp;
    a=1;
    b=10;
    printf("交换前:a=%d,b=%d\n\n\n",a,b);

    //方法1
    printf("通过临时变量交换---->完成值传递交换\n");
    temp=a;
    a=b;
    b=temp;
    printf("交换后:a=%d,b=%d\n\n\n",a,b);

    //方法2
    a=1;
    b=10;
    swap(a,b);
    printf("交换后:a=%d,b=%d\n\n\n",a,b);

    //方法3
    a=1;
    b=10;
    swap_p(&a,&b);//不要忘记&符号
    printf("交换后:a=%d,b=%d\n\n\n",a,b);

    //方法4
    printf("通过define宏交换---->完成值传递交换\n");
    a=1;
    b=10;
    swap_m(a,b,temp);
    printf("交换后:a=%d,b=%d\n\n\n",a,b);


    printf("hello world...\n");
    system("pause");
    return 0;
}

//默认按值传递,所以只会传a,b的拷贝,不会修改a,b本身
void swap(int x,int y)
{
    int temp;
    temp = x;
    x = y;
    y =temp;
    printf("拷贝---->完成值传递交换\n");
}


//指针也是值传递,只不过形参和实参指向的都是同一个内存地址,所以才能够修改实参的值...记住了哦
void swap_p(int *px,int *py)
{
    int temp;
    temp = *px;
    *px = *py;
    *py = temp;
    printf("指针---->完成值传递交换\n");
}

 

1交换

标签:地址   stdio.h   efi   int   iostream   按值传递   实参   pause   style   

原文地址:http://www.cnblogs.com/Froger/p/6771664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!