C++
[C++] ์ธ์ ์ ๋ฌ ๋ฐฉ์ : call-by-value์ call-by-reference
carsumin
2024. 10. 14. 22:10
call-by-value
- ์ค ๋งค๊ฐ๋ณ์์ ๊ฐ์ ํ์ ๋งค๊ฐ๋ณ์์ ๋ณต์ฌํ๋ ๋ฐฉ์
float FahrToC(float fahr){
fahr -= 32; // ํ์ ๋งค๊ฐ๋ณ์ ์์
return fahr * 5 / 9;
}
int main(){
float fTemp, cTemp;
cout << "ํ์จ์จ๋ : ";
cin >> fTemp;
cTemp = FahrToC(fTemp); // ์๋ณธ์ ๋ณํ ์์
cout << "์ญ์จ์จ๋ : " << cTemp << endl;
return 0;
}
- ์ฅ์ : ์ค ๋งค๊ฐ๋ณ์์ ํ์ ๋งค๊ฐ๋ณ์๋ ๋ณ๊ฐ์ ๋ฐ์ดํฐ์ด๋ฏ๋ก ๋ถ์์ฉ ๋ฐ์ x
- ๋จ์ : ๊ตฌ์กฐ์ฒด์ ๊ฐ์ด ๋ง์ ์์ ๋ฐ์ดํฐ๋ก ๊ตฌ์ฑ๋ ์ธ์๋ฅผ ์ ๋ฌํ ๊ฒฝ์ฐ ๋ณต์ฌ๋์ด ๋ง์์ง
call-by-reference
- ์ค ๋งค๊ฐ๋ณ์์ ์ฐธ์กฐ๋ฅผ ํ์ ๋งค๊ฐ๋ณ์์ ์ ๋ฌ
- ํจ์์์ ์ฒ๋ฆฌํ ๊ฒฐ๊ณผ๋ฅผ ๋งค๊ฐ๋ณ์๋ฅผ ํตํด ๋ฐ์ ์ค๋ ค๋ ๊ฒฝ์ฐ
- ๋ง์ ์์ ๋ฐ์ดํฐ๋ก ๊ตฌ์ฑ๋๋ ๊ตฌ์กฐ์ฒด๋ ๊ฐ์ฒด์ ๊ฐ์ ์ธ์๋ฅผ ํจ์์ ํจ์จ์ ์ผ๋ก ์ ๋ฌํ๋ ๊ฒฝ์ฐ
// call-by-reference ์์ : swap ์๊ณ ๋ฆฌ์ฆ
#include <iostream>
using namespace std;
void SwapValues(int& x, int& y);
int main(){
int a, b;
cout << "๋ ์๋ฅผ ์
๋ ฅ : ";
cin >> a >> b;
if (a<b) SwapValues(a, b); //a์ ํฐ ๊ฐ์ ๋ฃ์
cout << "ํฐ ์ = " << a << "์์ ์ = " << b << endl;
return 0;
}
void SwapValues(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}