#include <iostream>
using namespace std;
void swap(int px, int py) {
int temp = px;
px = py;
py = temp;
cout << "px addr = " << &px << endl;
cout << "py addr = " << &py << endl;
cout << endl;
}
int main() {
int x = 10, y = 20;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "x addr = " << &x << endl;
cout << "y addr = " << &y << endl;
cout << endl;
swap(x, y);
// x와 y의 주소와 px와 py의 주소가 다른것을 확인할 수 있음
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "x addr = " << &x << endl;
cout << "y addr = " << &y << endl;
}
x = 10
y = 20
x addr = 000000ADE32FF694
y addr = 000000ADE32FF6B4
px addr = 000000ADE32FF670
py addr = 000000ADE32FF678
x = 10
y = 20
x addr = 000000ADE32FF694
y addr = 000000ADE32FF6B4
함수를 실행할 시에 넘겨준 매개변수 값이 변경되지 않고 복사된 개체의 값이 변경되는 것을 알 수 있다.
#include <iostream>
using namespace std;
struct Weapon {
int price;
int power;
};
Weapon upgrade(Weapon weapon) {
weapon.power += 10;
weapon.price += 10;
return weapon;
}
int main() {
Weapon weapon{ 10, 20 };
cout << "price : " << weapon.price << endl;
cout << "power : " << weapon.power << endl;
weapon = upgrade(weapon); // weapon에 복사된 값을 할당하여 값이 변경됨.
cout << "upgrade" << endl;
cout << "price : " << weapon.price << endl;
cout << "power : " << weapon.power << endl;
return 0;
}
price : 10
power : 20
upgrade
price : 20
power : 30
위처럼 함수를 실행하여 복사된 인자를 넘겨주면 값이 변경된다.