交換兩個整數的方法比較

#include <iostream>

using namespace std;


void swap0(int x,int y)//形參的交換,沒有變化

{
int temp;
temp = x;
x = y;
y = temp;
}

void swap1(int *x,int *y)//指針傳遞(地址傳遞)形參是兩個整型指針,調用的時候傳入整型的地址,
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

void swap2(int &x,int &y)//引用傳遞,形參是兩個整型的引用,調用swap時,x,y初始化爲main函數中的x,y的別名,簡單高效!
{
int temp;
temp = x;
x = y;
y = temp;
}

void main()
{
int x = 10, y = 20;


cout<<"swap0 before:x = "<<x<<"  y = "<<y<<endl;
swap0(x,y);//傳值
cout<<"swap0  after:x = "<<x<<"  y = "<<y<<endl;
 
cout<<"swap1 before:x = "<<x<<"  y = "<<y<<endl;
swap1(&x,&y);//傳地址(傳指針)
cout<<"swap1  after:x = "<<x<<"  y = "<<y<<endl;
 
cout<<"swap2 before:x = "<<x<<"  y = "<<y<<endl;
swap2(x,y);//(引用)
cout<<"swap2  after:x = "<<x<<"  y = "<<y<<endl;
system("pause");

}


運行結果:

swap0 before:x = 10  y = 20
swap0  after:x = 10  y = 20
swap1 before:x = 10  y = 20
swap1  after:x = 20  y = 10
swap2 before:x = 20  y = 10
swap2  after:x = 10  y = 20 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章