Call by Value
When you pass an argument to a function, the function receives a copy of the argument. After the function call, the passed argument remains unchanged, even if the called function modifies the received argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @ <stdio.hdr> fn foo(n: int) { printf("foo entered: n = %d\n", n); n = 42; printf("foo leaving: n = %d\n", n); } fn main() { local n: int = 123; printf("main: n = %d\n", n); printf("calling foo:\n"); foo(n); printf("returned from foo\n"); printf("main: n = %d\n", n); } |
Task
-
Translate the program and execute it. Go through the program line by line again to understand which output is generated in which line. Confirm the claim that a function only receives a copy (and not the original) of the argument. On my computer, I get the following output:
theon$ abc ex4.abc theon$ ./a.out main: n = 123 calling foo: foo entered: n = 123 foo leaving: n = 42 returned from foo main: n = 123 theon$
-
To clarify that the caller of a function can name the argument differently than the callee, make the following change: Rename the local variable in function main to x.