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. πŸš€


17 Programming Foundations - Variables.pdf
Complete and Continue  
Discussion

5 comments