#include <iostream>
using namespace std;
void call_by_value(int x, int y){
int temp = x;
x=y;
y=temp;
}
void swap_pointer(int *x, int *y){
int temp = *x; //x 포인터가 가리키는 값
*x = *y;
*y= temp;
}// call by reference
void swap_reference(int &x, int &y){
int temp = x;
x=y;
y=temp;
} // reference 매개 변수로 받음과 동시에 초기화하면서 같은 주소값을 갖게됨
int main(){
int first =0, second = 1;
cout<<"first="<<first<<" "<<"second="<<second<<endl;
cout<<"swap_pointer"<<endl;
swap_pointer(&first, &second);// 매개 변수가 포인터 변수 임으로 주소값을 넘겨 줘야함.
cout<<"first="<<first<<" "<<"second="<<second<<endl;
cout<<endl;
cout<<"swap_reference"<<endl;
swap_reference(first, second); // 매개변수가 reference임으로 그냥 변수 넘겨줌.
cout<<"first="<<first<<" "<<"second="<<second<<endl;
cout<<endl;
cout<<"call_by_value"<<endl;
call_by_value(first,second);
cout<<"first="<<first<<" "<<"second="<<second<<endl;
system("pause");
return 0;
}
first=0 second=1
swap_pointer
first=1 second=0
swap_reference
first=0 second=1
call_by_value
first=0 second=1
댓글