This line of questioning (how do I know what happens to variables and when) is usually very language-dependent, so it’s often a lot more relevant to talk about it in the context of a specific language. However, in the example you present, I think there is a general answer:
For the code:
var1 = 1
var2 = var1
var2 = var2 + 3
On line 2, there are two things that could happen:
- var2 gets assigned the value 1
- var2 now points to the same location in memory as var1, and var1’s location in memory holds the value 1
If #1 happens, we get the behavior you see above. This should not be surprising.
If #2 happens, now var1 and var2 point to the same location in memory. Your question is why isn’t this the case? Consider, if line 2 does make var2 point to the same thing as var1, what does line 3 do?
...
If x = y
makes x point to the thing y points to, what does x = y + 3
do? Make x point to the thing y + 3 points to? This doesn’t really make sense.
What this gets at, underneath, is the difference between a value, a variable, and a pointer. In the example you give, var1 and var2 are variables, which on the left hand side of an equals sign are treated as such (you can assign values to your variables e.g. x = 3
). But on the right-hand side of an equals sign, variables become their values before other operations take place. In var2 = var1 + 3
, the expression becomes var2 = 1 + 3
and then var2 = 4
.
In some languages, this behavior is not always automatic. Instead, you have to create it for yourself, by using pointers. This effectively means you have one way of referencing a variable x
which explicitly says you want the location in memory x points to, which is the true “value of x”, and another way of referencing it x’
which explicitly says you want the value at that location in memory.
In such a world, your code could be written as
var1’ = 1
var2’ = var1’
var2’ = var2’ + 3
To get behavior #1 above, or
var1’ = 1
var2 = var1
var2’ = var2’ + 3
To get output
4
4
All this assuming that var1 and var2 have been initialized beforehand.
In such languages (like C) you can actually do things like `x = y + 3’, where x and y are pointers. It literally makes x equal to the position in memory three spots further along than y. This is called pointer arithmetic.