|
|
|
|
The programming language that I will use is Java -- because you are familiar with Java.
But realize that:
|
|
|
Let us assume that the addresses of the variables are as follows:
|
|
|
Notice that:
|
|
|
|
Questions:
|
Answer:
2.0 (the value in x is CHANGEDD !!!!!!) 6.0 (the value in y is CHANGEDD !!!!!!) 8.0 (= 2.0 + 6.0) |
Did you understand why the update statements "a = a + 1" and "b = b + 2" change the actual parameters x and y ???
|
|
a = a + 1; |
will change the values of the actual parameter variable x through the following mechanism:
|
Similarly, the assignment statement:
b = b + 1; |
will change the values of the actual parameter variable y to 6.0 (not shown)
|
That's why, if we could use the pass-by-reference mechanism, the statements would print:
System.out.println(x); ---> prints 2.0 System.out.println(y); ---> prints 6.0 |
|
using the C++ language (because C++ provide both mechanisms)
| Pass-by-value | Pass-by-reference |
|---|---|
// No & means: pass-by-value
double fun ( double a, double b )
{
double m;
a = a + 1;
b = b + 2;
m = a + b;
return(m);
}
int main(int argc, char **argv)
{
double x = 1.0, y = 4.0;;
double r;
r = fun( x, y );
cout << x << endl;
cout << y << endl;
cout << r << endl;
}
|
// With & means: pass-by-reference
double fun ( double & a, double & b )
{
double m;
a = a + 1;
b = b + 2;
m = a + b;
return(m);
}
int main(int argc, char **argv)
{
double x = 1.0, y = 4.0;;
double r;
r = fun( x, y );
cout << x << endl;
cout << y << endl;
cout << r << endl;
}
|
Output:
1
4
8
|
Output:
2
6
8
|
How to run the programs:
|