void sub1(int x) { printf("%d\n",x); // cout << x << eoln; }
This is a fairly simple example that prints the value of parameter x
to the standard output. Now, let us consider an invocation (call) of the
subroutine:
sub1(z);
In this invocation, the expression z
is evaluated, then a copy of
this value is given to subroutine sub1
. Because we are only working
with a copy of the expression, we can use any expression that evaluates
to an integer value, such as the following:
sub1(z*z+10*y);
You can consider pass-by-value as a safe method to provide extra information to a subroutine. This is because the subroutine cannot change the value of any variable or object that belongs to the caller. Let us consider another example:
void inc(int x) { x = x + 1; }
A good compiler should give you a warning. This is because what we do to
parameter x
remains local to the subroutine. We can incrementing
a copy of whatever expression is used to specify the argument. For
example, we may have the following invocation:
inc(z);
What is provided to subroutine inc
is not a method to find
variable z
, but rather just the current value of z
.
Parameter x
in subroutine sub1
works with a copy of the
value of z
. The incremented value is not related to variable
z
, at all.
In other words, if you have an object or variable to be altered by a subroutine, pass-by-value should not be used.
Copyright © 2006-08-28 by Tak Auyeung