์ฐธ์กฐ๋ณ€์ˆ˜์™€ ์ผ๋ฐ˜๋ณ€์ˆ˜์˜ ์‚ฌ์šฉ์˜ ์ฐจ์ด์ ์„ ์•Œ์•˜๋‹ค๋ฉด, main ํ•จ์ˆ˜๊ฐ€ ๋™์ž‘ํ•˜๋Š” ๋„์ค‘ ๋‹ค๋ฅธ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ• ๋•Œ, ๊ทธ ํ•จ์ˆ˜์˜ ์ธ์ž ์—ญ์‹œ ๋‘ ์ข…๋ฅ˜๊ฐ€ ์žˆ์Œ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ผ๋ฐ˜๋ณ€์ˆ˜์™€, ์ฐธ์กฐ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋‘ ๋ณ€์ˆ˜์˜ ๊ฐ’์„ ๋ฐ”๊พธ๋Š” ํ•จ์ˆ˜ย swapย ์„ main ํ•จ์ˆ˜์—์„œ ํ˜ธ์ถœํ•˜๋Š” ์ƒํ™ฉ์„ ๊ฐ€์ •ํ•˜๊ณ  ๋น„๊ตํ•ด๋ณด์ž.

Swap_callbyValue

#include <iostream>
 
using namespace std;
 
int swap(int a, int b){
    int temp = a;
    a = b;
    b = temp;
    
    return 0;
}
 
int main(){
    int x = 5, y = 10;
    cout << "x = " << x << ", y = " << y << endl;
    swap(x, y);
    cout << "x = " << x << ", y = " << y << endl;
    
    return 0;
}
์ถœ๋ ฅ
// x = 5, y = 10
// x = 5, y = 10

์™œ ๊ฐ™์€ ๊ฐ’์ด ์ถœ๋ ฅ๋ ๊นŒ? mainย ํ•จ์ˆ˜์—์„œย swapย ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ–ˆ์„ ๋•Œ, xย ,ย yย ๊ฐ’์ดย swapย ํ•จ์ˆ˜์— ๋“ค์–ด๊ฐ€๊ณ , ์ด ๊ฐ’์€ ๊ฐ๊ฐย aย ,ย bย ์—ย ๋ณต์‚ฌย ๋œ๋‹ค.

๋”ฐ๋ผ์„œย swapย ํ•จ์ˆ˜ ์•ˆ์—์„œ๋Š”ย ๋ณต์‚ฌ๋œ a, bย ์•ˆ์— ๋“ค์–ด๊ฐ„ ๊ฐ’์ด ์„œ๋กœ ๋ฐ”๋€Œ๊ฒŒ ๋˜๊ณ , swapย ํ•จ์ˆ˜๊ฐ€ ์ข…๋ฃŒ๋œ ํ›„์— ์ด ๊ฐ’์€ย ์‚ฌ๋ผ์ง„๋‹ค.

๊ฒฐ๊ตญ ๋‚ด๊ฐ€ ์›ํ•œ ๊ฒฐ๊ณผ์ธย xย ,ย yย ๋Š” ๋ฐ”๋€Œ์ง€ ์•Š๋Š”๊ฒŒ ๋‹น์—ฐํ•˜๋‹ค. ์ด๋ ‡๊ฒŒ ๊ฐ’์ด ๋ณต์‚ฌ๋˜์–ด ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์„ย callbyvalueย ๋ผ ํ•œ๋‹ค.

Swap_callbyReference

#include <iostream>
 
using namespace std;
 
int swap(int &a, int &b){
    int temp = a;
    a = b;
    b = temp;
    
    return 0;
}
 
int main(){
    int x = 5, y = 10;
    cout << "x = " << x << ", y = " << y << endl;
    swap(x, y);
    cout << "x = " << x << ", y = " << y << endl;
    
    return 0;
}
์ถœ๋ ฅ
// x = 5, y = 10
// x = 10, y = 5

์ด๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ,ย swapย ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ ๋’ค์— ์•ˆ์— ๋“ค์–ด๊ฐˆ ๋•Œ,ย &a = xย ,ย &b = yย ์ด๋Ÿฐ์‹์œผ๋กœ ๋“ค์–ด๊ฐ€๊ธฐ ๋•Œ๋ฌธ์—

aย ์™€ย bย ๋Š”ย xย ,ย yย ์ž์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค. ๋”ฐ๋ผ์„œ ๋‚ด๊ฐ€ ์›ํ•˜๋Š” ๊ฒฐ๊ณผ์ธย xย ,ย yย ์˜ ๊ฐ’์ด ๋ฐ”๋€Œ๊ฒŒ ๋œ๋‹ค.

์ด๋ ‡๊ฒŒ ์‹ค์ œ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์„ย callbyreferenceย ๋ผ ํ•œ๋‹ค.