Computer Language/C++

[C++] call by value & call by reference

정우섭 2020. 3. 21. 23:50

call by value : This method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function.

 

The parameter of the functuin gets the copies of the value.

 

So every calculation in the function using the parameter does changes the value of the parameter in the function, but it doesn't change the original variables which passed the value to the parameter.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
  
void swap(int swap_val1, int swap_val2);
  
int main()
{
    int val1 = 10;
    int val2 = 20;
    swap(val1, val2);
  
    cout<<"val1 : "<<val1<<endl;
    cout<<"val2 : "<<val2<<endl;
  
    return 0;
}
  
void swap (int swap_val1, int swap_val2)
{
    int temp = swap_val1;
    swap_val1 = swap_val2;
    swap_val2 = temp;
  
    cout<<"swap_val1 : "<<swap_val1<<endl;
    cout<<"swap_val2 : "<<swap_val2<<endl;
}
 

 

 

Result

 
 
 
 
swap_val1 : 20
swap_val2 : 10
val1 : 10
val2 : 20
 

 

If a parameter's value is changed in a function.

 

It doesn't change the variable itself, it only changes the copy of the variables value.

 

And that is "call by value".

 

 

 

call by reference :  This method of passing arguments to a function copies the reference of an argument into the formal parameter. Reference is used to access the actual argument in the function. This means that the value of the parameter will be passed to the original variable.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;
 
void swap(int &swap_val1, int &swap_val2);
 
int main () {
   int val1 = 10;
   int val2 = 20;
 
   cout << "val1 : " << val1 << endl;
   cout << "val2 : " << val2 << endl;
 
   swap(a, b);
 
   cout << "swap_val1 : " << val1 << endl;
   cout << "swap_val2 : " << val2 << endl;
 
   return 0;
}
 
void swap(int &swap_val1, int &swap_val2) {
   int temp;
   temp = swap_val1;
   swap_val1 = swap_val2;
   swap_val2 = temp;
  
    cout<<"swap_val1 : "<<swap_val1<<endl;
    cout<<"swap_val2 : "<<swap_val2<<endl;
 
   return;
}
 
 

 

Result

 

1
2
3
4
5
6
val1 : 10
val2 : 20
swap_val1 : 20
swap_val2 : 10
swap_val1 : 20
swap_val2 : 10
 

 

 

 

 

 

 

 

 

 

[참고자료]

- 윤성우의 열혈 C++ 프로그래밍