Where values live and what names point to: memory and references
While a program runs, every value we make has to live somewhere. That place is memory. Picture a long wall of numbered lockers. A name is a note pointing to one of those lockers.
Every value lives somewhere
All the while a program runs,
every value takes a spot somewhere in memory.
Memory is like a wall lined with numbered lockers.
Make a value, and it slips into one empty slot.
The program remembers a value by 'which slot number'.
Press 'store a value'. It goes into an empty slot, and you see the slot number.
Each value got its own slot and number.
But in code we don't write 'slot 7', do we?
We write names like 'a', 'score'.
So how does that name connect to a slot number?
A name points to a slot
A name isn't the value itself.
It's a note that knows 'which slot'.
Name 'a' -> slot 3 -> the 7 inside.
So when you use 'a', the program follows the note,
opens slot 3 and reads 7. This is what 'pointing' means.
Tap the name 'a'. It follows the note to the slot and pulls out the value.
The name points to a slot, and the value is inside that slot.
This 'pointing note' is called a reference.
Now, from here on is what really matters.
If you say 'give a to b as well', what happens?
A small value gets copied
Give a small value like a number to b,
and that value is duplicated into a new slot.
Now a is slot 3, b is slot 5. Different slots.
So even if you change a to 9, b stays 7.
The two are independent, each holding its own value.
Press 'copy to b', then 'change a'. b is a different slot, so it doesn't change.
Copied small values don't affect each other. Clean.
But a big thing like an object is a different story.
Duplicating a big thing wholesale is heavy.
So, often, instead of copying, something else happens.
Big things share one slot
When you give an object to b, instead of duplicating the whole object,
often b is made to point at the same slot.
Now a and b, two notes, point at one slot together.
So if you change that object through a,
looking through b shows the same change. One thing with two names.
Two names pointing to one slot means changing one changes both.
It's the spot that surprises people most when first learning.
'Why did b change when I never touched it?'
Now you know the answer: they were pointing to the same slot.
Know what points where, and the confusion ends
The confusion always comes down to one thing.
Does a name hold its own copy, or share a pointer to one thing?
Small value: it's a copy, so they move apart.
Big thing: they point to one slot, so they move together.
Just recall this distinction, and surprises disappear.
Pick 'small value' vs 'big thing' and do the same thing. See the outcomes split.
This is the foundation of programming.
From a single value, we bundled, repeated, and named,
gathered into objects, fixed by debugging, and let a machine run it.
And now we've seen where all of it lives
and what the names point to. A solid foundation is in place.