Variables & Constants: How Programs Store Data
Variables & Constants: How Programs Store Data
Programs need a place to store information while they run.
That place is a variable—a named container in memory that holds a value you can read and change. Sometimes you also need a constant—a container you cannot change after setting it.
In this lesson you’ll see how data lives in memory cells, what a memory address is, what an identifier means, and how to choose the right type without wasting memory.
1️⃣ What is a Variable?
🔹 A variable is a container for storing data values you’ll reuse during program execution.
🔹 Think “kitchen containers”: you pick the right size and label it for what it holds.
2️⃣ Anatomy of a Variable (RAM view)
For a single variable you always have:
- Address (e.g.,
0x7fff...) → Location in memory (hexadecimal) - Type (e.g., Int, Float, String, Boolean)
- Identifier (Name) (e.g.,
Age) - Value (e.g.,
45) - Memory Cell (the physical slot that holds the bits)
Program can change the variable content at runtime :
Example :
- Type:
Int - Identifier (Name):
Age - Value:
45 - Memory cell: a slot in RAM that actually stores the bits
- Memory address: where this cell lives (shown in hex, e.g.,
0x7fff5694dc58)
Updating a variable:
Age = Age + 2 → from 45 to 47. The same cell gets a new value.
3️⃣ Primary Variable Types
- Integer (Int): whole numbers (e.g.,
0, 45, −3) - Float/Double: numbers with fractions (e.g.,
3.14) - String: text (e.g.,
"Mohammed") - Boolean:
True/False(1/0)
4️⃣ What is a Constant?
🔹 A constant is also a container for storing data, but read-only after initialization.
🔹 If you try to assign a new value → Error.
Example: Const Float PI = 3.14 → PI = PI + 2 ❌ (not allowed).
5️⃣ Performance Tips — Don’t Waste Memory!
- Choose the smallest sensible type for the real-world range.
- Example : human Age will never be 4,294,967,295; typical max ~150 → don’t reserve a huge type unnecessarily.
- Fewer/lighter variables → fewer memory space → better performance.
🧬 Characteristics
- 1️⃣ Variable → mutable (can be changed) value in a memory cell.
- 2️⃣ Constant → immutable (cannot be changed) value; compile/runtime prevents changes.
- 3️⃣ Identifier → human-friendly name bound to a memory location.
- 4️⃣ Address → precise location in RAM (shown in hexadecimal).
- 5️⃣ Type → defines what kind of data and how much memory to use.
🔗 Interconnection
- Type decides size/format → impacts performance and limits.
- Identifier ↔ Address: name you use vs where it lives in RAM.
- Variable vs Constant: mutable vs read-only; both are containers but with different rules.
By carefully choosing names, types, and mutability, you write code that’s clear, safe, and fast. 🚀











0 comments