|
void f(int a, int b) { // don't care what happens inside the function... } |
|
So:
|
|
|
(There are others, e.g., pass-by-name)
In the pass-by-value method, the value of the actual parameter is copied into the (formal) parameter variable |
In the pass-by-value method, the address (reference) of the actual parameter is copied into the (formal) parameter variable |
Example:
void f ( int a, int b ) { .... } |
void f(int a, int b) { cout << "Before increment a = " << a << ", b = " << b << "\n"; a = a + 10000; // Update the parameter variables b = b + 10000; cout << "After increment a = " << a << ", b = " << b << "\n"; } int main(int argc, char *argv[]) { int x, y; x = 10; y = 100; cout << "Before f(x,y), x = " << x << ", y = " << y << "\n"; // prints: x = 10, y = 100 (not surprising) f(x, y); // Pass-by-value: copy x to a, y to b cout << "After f(x,y), x = " << x << ", y = " << y << "\n"; // prints: x = 10, y = 100 (unchanged) !!! } |
The following figure shows what is going on inside the computer when parameters are passed "by value":
Step by step:
|
Example:
void f ( int & a, int & b ) { .... } |
void f(int & a, int & b) <------ Only change !!! { cout << "Before increment a = " << a << ", b = " << b << "\n"; a = a + 10000; // Update the parameter variables b = b + 10000; cout << "After increment a = " << a << ", b = " << b << "\n"; } int main(int argc, char *argv[]) { int x, y; x = 10; y = 100; cout << "Before f(x,y), x = " << x << ", y = " << y << "\n"; // prints: x = 10, y = 100 (not surprising) f(x, y); // Pass-by-value: copy x to a, y to b cout << "After f(x,y), x = " << x << ", y = " << y << "\n"; // prints: x = 10010, y = 10100 (changed) <----- !!! } |
The following figure shows what is going on inside the computer when parameters are passed "by reference":
Step by step:
|
Example:
void compute( double & sum, double & diff, double & prod, double & quot, double a, double b) { sum = a + b; diff = a - b; prod = a * b; quot = a / b; } |
void f( int a[] ) // No special & symbol... { a[0] = 10000 + a[0]; // will update actual parameter a[1] = 10000 + a[1]; a[2] = 10000 + a[2]; a[3] = 10000 + a[3]; } |