call-by-reference & call-by-value

2022. 4. 2. 02:06C++

call-by=reference: 주소 값을 인자로 전달하는 함수의 호출 방식

call-by-value: 값을 인자로 전달하는 함수의 호출 방식

#include<iostream>
using namespace std;

void changeVal(int val1, int val2)
{
    int temp;
    temp = val1;
    val1 = val2;
    val2 = val1;
}

void changeRef1(int &ptr1, int &ptr2) // 참조자를 이용한 call-by-reference
{
    int temp;
    temp = ptr1;
    ptr1 = ptr2;
    ptr2 = temp;

}

void changeRef2(int *ptr1, int *ptr2)
{
    int temp;
    temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;

}
int main()
{
    int num1 = 10;
    int num2 = 50;
    
    changeVal(num1, num2);
    cout<<"changeVal function excute!"<<endl;
    cout<<"num1: "<<num1<<", num2: "<<num2<<endl;   // num1: 10, num2: 50
    
    changeRef1(num1, num2);
    cout<<"changeRef1 function excute!"<<endl;
    cout<<"num1: "<<num1<<", num2: "<<num2<<endl;   //num1: 50, num2: 10
	
    changeRef2(&num1, &num2);
    cout<<"changeRef2 function excute!"<<endl;
    cout<<"num1: "<<num1<<", num2: "<<num2<<endl;   //num1: 10, num2: 50

}

'C++' 카테고리의 다른 글

new와 delete  (0) 2022.04.03
malloc & free  (0) 2022.04.03
Reference  (0) 2022.04.03
template  (0) 2022.04.02
pointer  (0) 2022.04.02