Tuesday, April 19, 2005
Call by Value vs Call by Reference
Seems the only difference is the method declaration:
func(int a, int b, int c)
func(int &a, int &b, int &c)
In both cases, the calling would be the same:
func(a, b, c);
Here is the code:
#include
using namespace std;
void func1(int a, int b);
void func2(int &a, int &b);
void func3(int *a, int *b);
void main(){
int a = 5;
int b = 10;
func1(a, b);
cout << "After func1: " << a << " " << b << endl;
func2(a, b);
cout << "After func2: " << a << " " << b << endl;
func3(&a, &b);
cout << "After func3: " << a << " " << b << endl;
}
void func1(int a, int b){
a = 3;
b = 6;
return;
}
void func2(int &a, int &b){
a = 3;
b = 6;
return;
}
void func3(int *a, int *b){
*a = 4;
*b = 8;
return;
}
In a sense, if you it's a pointer, you have to pass a pointer in; if it's call by value or call by reference, you just need to pass the variable in. The program knows the rest.
func(int a, int b, int c)
func(int &a, int &b, int &c)
In both cases, the calling would be the same:
func(a, b, c);
Here is the code:
#include
using namespace std;
void func1(int a, int b);
void func2(int &a, int &b);
void func3(int *a, int *b);
void main(){
int a = 5;
int b = 10;
func1(a, b);
cout << "After func1: " << a << " " << b << endl;
func2(a, b);
cout << "After func2: " << a << " " << b << endl;
func3(&a, &b);
cout << "After func3: " << a << " " << b << endl;
}
void func1(int a, int b){
a = 3;
b = 6;
return;
}
void func2(int &a, int &b){
a = 3;
b = 6;
return;
}
void func3(int *a, int *b){
*a = 4;
*b = 8;
return;
}
In a sense, if you it's a pointer, you have to pass a pointer in; if it's call by value or call by reference, you just need to pass the variable in. The program knows the rest.