Why is it by-reference and not by value?

66 views Asked by At

I was doing some revision for an upcoming test and came across this question:

Question

The answer in the mark scheme says:

Answer

However, I though it would be the other way round. I thought that FoodList would be passed by value and foods by reference given that foods is changed. Can you explain why it's the other way round?

Update: The answer could be wrong, there are a number of mistakes in the mark scheme.

1

There are 1 answers

0
Frank Puffer On BEST ANSWER

The only explanation I have is that the author has mixed up "by value" and "by reference".

However, if performance plays any role, FoodList should also be passed as reference because it is normally less expensive to copy the reference than to copy the whole string. Some languages like C++ let you mark a reference as being constant. This will prevent the subprogram from modifying its value.

Also, in most programming languages, subprograms are called functions and have return values. It is good practice to use the arguments only for inputs and the return value for the output of a subprogram. (To find out why this is good practice, search for the terms "side effects" and "referential transparency".)

In C++ the function could be declared as follows:

std::list<std::string> Make_List( const std::string& foodList );