DEV Community

Aanand
Aanand

Posted on

How your compiler finds the data that is stored inside the variable (Symbol table)

Have you ever typed print(variable_name) and wondered how your compiler actually finds the data by using variable name? It's like magic, but there's a fascinating process working behind the scenes!

Variables are like house Addresses
Think of computer memory like a giant apartment building with millions of rooms. Each room has a number address like "Room #0x1000.

when you write:

int num = 37;
Enter fullscreen mode Exit fullscreen mode

Here's what happens:

  1. Find an empty room: The compiler finds an available memory location (say, room #0x1000)

  2. Move in the value: The number 37 moves into this room.

  3. Put up a name tag: The variable name "num" becomes the friendly name for this address.

The Compiler's Secret Address Book
So when your program actually runs, all those name tags disappear! how does
cout << num still work?
The compiler keeps a secret address book called a symbol table:

┌────────────┬──────────────────┐
│ Variable   │ Memory Address   │
├────────────┼──────────────────┤
│ num        │ 0x1000           │
│ age        │ 0x1004           │
│ name       │ 0x2000           │
└────────────┴──────────────────┘
Enter fullscreen mode Exit fullscreen mode

When you print a variable:

cout << num;
Enter fullscreen mode Exit fullscreen mode

The compiler:

  1. Looks up "num" in its address book

  2. Finds it lives at memory address 0x1000

  3. Sends instructions: "Go to address 0x1000 and print what's inside!"

Variable names are for humans — memory addresses are for compiler!

Top comments (0)