#include<iostream>
using namespace std;
void SwapWayOne(int* x, int* y){
int temp = 0;
temp = *x;
*x = *y;
*y = temp;
}
void SwapWayTwo(int &x, int &y){
int temp = 0;
temp = x;
x = y;
y = temp;
}
void failedSwapWay(int x, int y){
int temp = 0;
temp = x;
x = y;
y = temp;
}
inline void inlineSwapWayOne(int* x, int* y){
//address of x: 0x6ffde0, address of y: 0x6ffde8
cout << "address of x: " << &x << ", " << "address of y: " << &y << endl;
//value of address x: 0x6ffe0c, value of address y: 0x6ffe08
cout << "value of address x: " << *(&x) << ", " << "value of address y: " << *(&y) << endl;
//value of address x: 0x6ffe0c, value of address y: 0x6ffe08
cout << "value of address x: " << x << ", " << "value of address y: " << y << endl;
//value of x: 5, value of y: 9
cout << "value of x: " << *x << ", " << "value of y: " << *y << endl;
int temp = 0;
temp = *x;
*x = *y;
*y = temp;
}
inline void inlineSwapWayTwo(int &x, int &y){
//address of x: 0x6ffe0c, address of y: 0x6ffe08
cout << "address of x: " << &x << ", " << "address of y: " << &y << endl;
//value of x: 5, value of y: 9
cout << "value of x: " << *(&x) << ", " << "value of y: " << *(&y) << endl;
//value of x: 5, value of y: 9
cout << "value of x: " << x << ", " << "value of y: " << y << endl;
int temp = 0;
temp = x;
x = y;
y = temp;
}
inline void failedSwapThoughInline(int x, int y){
int temp = 0;
temp = x;
x = y;
y = temp;
}
int main(){
int numA = 5, numB = 9;
cout << "Original order: " << numA << ", " << numB << endl;
// failedSwapWay(numA, numB);
// SwapWayOne(&numA, &numB);
// SwapWayTwo(numA, numB);
// inlineSwapWayOne(&numA, &numB);
inlineSwapWayTwo(numA, numB);
// failedSwapThoughInline(numA,numB); // inline function‘s scope is still inside!
cout << "After changed: " << numA << ", " << numB <<endl;
return 0;
}
作者:艾孜尔江·艾尔斯兰
原文:https://www.cnblogs.com/ezhar/p/13760342.html