The CPU has
+
, <
, etc.)
int healthRisk(int cigarettesPerDay, int poundsOverWeight, int exerciseHoursPerWeek) { int smokingRisk = 20 * Math.sqrt(cigarettesPerDay); int weightRisk = poundsOverweight - 8; return smokingRisk + weightRisk - square(exerciseHoursPerWeek); } int square(i) { return i * i; }Let's look at the execution stack for the call
healthRisk(4, 15, 3)
.
Call by Value
Let's think about what's going on in the example we just did.
When a procedure is called, space is created on the stack for the
What happens to the calling procedure if we assign to a parameter within the called procedure? For example,
int foo(int x, int y) { int z = bar(x); return x + y + z; } int bar(int x) { x = 5 * x; if (x > 10) return x; else return -x; }What is the return value from
foo(3, 10)
?
x
to
foo
is different from the parameter
x
to bar
.
x
inside bar
, the
x
in foo
is unaffected.
x
in foo
is unchanged -- the
parameter value is not copied back on return.
The value of the actual parameter is copied into the formal parameter and used locally.Call-by-value is the parameter passing mechanism used by Java. (Some languages, such as C++, permit call-by-reference, where the called procedure uses a variable provided by the calling procedure. With call-by-reference, changes to the value of the variable are visible to the calling procedure upon return.)
Let's do one more example:
int foo(int x, int y, int z) { return z + bar(x, y); } int bar(int z, int w) { int x = z + w; z = square(z); return x + z; } int square(int x) { return x * x; }What is the return value of
foo(3, 4, 5)
?
Kennneth J. Goldman Last modified: Mon Jan 20 15:50:36 CST