#021 – Thinking in memory. What a variable ACTUALLY is

Recap

Literals are hardcoded values such as 5 or "Hello world!". They cannot be changed after runtime.

A variable also holds a value. But not quite.

A variable is a representation of a value that is stored at a memory address. It represents a memory location where the value is stored, NOT the value itself.

There is a slight nuance.

What a variable really is

A variable is not a value.

It’s a representation of a value stored at a memory address. The variable’s name is a label for a memory location; the value just happens to live there

int x = 11;

What actually happens here is:

  1. The compiler reserves a portion of memory large enough to hold an int. Let’s assume 4 bytes, which is standard on a typical architecture.
  2. It associates the name x with the address of that memory.
  3. It writes the bit pattern representing 11 into that location.

Takeaway: Why this distinction is important

Once you start thinking of variables as memory locations rather than values, more advanced C++ features stop feeling mysterious.

For example, references and pointers are both expand on this concept.

A reference is another name for the same memory location, and a pointer is a variable whose value is itself a memory address.

Leave a Reply

Your email address will not be published. Required fields are marked *