본문 바로가기

Programming/C++ 1

[C++] Swap Function

반응형
#include <iostream>
using namespace std;
void swap_passByVal(int n1, int n2);
void swap_passByRef(int& n1, int& n2);
void swap_passByPtr(int* p1, int* p2);

int main() {
	int num1 = 50, num2 = -60;
	cout << "main add of num1, num2 : " << &num1 << " " << &num2 << endl;
	swap_passByVal(num1, num2);
	cout << "After swap_passByVal num1, num2 : " << num1 << " " << num2 << endl;
	swap_passByRef(num1, num2);
	cout << "After swap_passByRef num1, num2 : " << num1 << " " << num2 << endl;
	swap_passByPtr(&num1, &num2);
	cout << "After swap_passByPtr num1, num2 : " << num1 << " " << num2 << endl;

	return 0;
}

void swap_passByVal(int n1, int n2) {
	cout << "Swap Pass By Val : address of n1, address of n2 : " << &n1 << " " << &n2 << endl;
	int temp = n1;
	n1 = n2;
	n2 = temp;
}
void swap_passByRef(int& n1, int& n2) {
	cout << "Swap Pass By Ref : address of n1, address of n2 : " << &n1 << " " << &n2 << endl;
	int temp = n1;
	n1 = n2;
	n2 = temp;
}

void swap_passByPtr(int* p1, int* p2) {
	cout << "Swap Pass By Ptr : address of p1, address of p2 :" << &p1 << " " << &p2 << endl;
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}

 

반응형