CS Question (Value vs Reference)Watch
Please could I get help on this... I don't understand why the outputs are as shown?
When you call a function or procedure, that procedure has its own memory space on an area of memory known as "the stack"
When a variable is passed to a function or procedure "by value", then the variable's data is copied into a new variable in the function's stack. If a function/procedure tries to modify a by-value argument, then the memory area which is modified will be the one which belongs to that function's stack. The original variable will not change.
When a variable is passed to a function or procedure "by reference", then the value is not copied, instead the variable's area of memory becomes visible (and therefore directly modifiable) by the function - so when the function modifies it, the original variable will change.
For a bit of technical background. Loosely speaking, there are generally 2 types of variables in a programming language; usually called Reference variables and Primitive variables.
Primitive variables are, as their name suggests, fairly simple - they're a bit of memory, and they're only visible within the "scope" of the code which creates them (for example - if a primitive variable is created inside a function, then nothing outside of that function can possibly see nor modify it)
A reference variable is a bit of an unnatural concept, because a reference is a value which "refers to" something in memory (so it can refer to a primitive variable among other things). Reference variables do not contain any meaningful data, they're like a memory bookmark for another variable.
Reference variables are useful because their purpose is to tell other parts of a program about bits of memory which are being used. So, when a reference variable is used in a function, it means "Hey, function - here's a variable, but the memory belongs to some other part of the program - you can access this memory, and you can modify its content, even though it doesn't really belong to you".
-- So, in answer to your assignment - trace through the code carefully and consider at each stage whether the variable being modified is a primitive, or whether it's a reference. If a variable is a reference, make sure you know which primitive it refers to.
Hint: There are 5 primitives in your code and 2 references.
The Main procedure has 2 primitives called p and r
The DoSomething procedure has 2 primitives called x and z
The DoSomethingElse procedure has 1 primitive called x
The DoSomething Procedure has a reference called y -- its referred-to primitive from the Main procedure is 'p'
The DoSomethingElse procedure has a reference called y -- its referred-to primitive from the DoSomething procedure is 'z'