1

I have this question about passing methods and I want to make sure I understand it correctly

What is the value of i and array a if arguments are passed by a value b reference c value/result asseume we have the following pseudocode

enter image description here

this is my answer

 By value i = 1 a[1]=10 a[2]=11 by reference i = 3 a[1] = 2 a[2] = 11 by value result i = 2 a[1] = 10 a[2] = 1 

is this correct ? thanks

1
  • so a[2] will never change here? it will be always a[2] = 11 ? Commented May 10, 2016 at 0:47

1 Answer 1

1

First of all, when you call a function (or procedure, whatever you name it), a new call stack is created. On that call stack, the parameters are assigned to values (parameters are the ones which is part of your function signature. Usually we call them 'formal parameters', like the x y z in your above procedure f). What they are assigned to is according to the actual arguments by which the function is invoked.

If they are passed by values, the formal parameters are assign to the values of the arguments. That means, the values of the actual arguments are copied to the formal parameters. Any further operations on the formal parameters does not affect the argument at all. In your example, y is assigned to the value of a[1], which is 10. In the function's body, y is reassigned, but nothing happened to a[1] anymore.

If they are passed by reference, on the other hand, the formal parameters are assigned to the memory address of the actual arguments, and in the function's body, the formal parameters are implicitly dereferenced to the values of that memory address. In your example, x will hold the memory address of i, y for a[1] and z for i as well. Operation on x y z are actually operation on i and a[1].

I don't know what you mean by "passed by value result". I have never seen such terms elsewhere.

Another thing I want to mention is, there are two distinct meanings of "reference" in the programming world. There will be no time for me to give a long explanation. You may search for "reference type in Java" and "reference variables in C++" to see the difference.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.