0
0
C++programming~3 mins

Why Constants and literals in C++? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if changing one number could fix your whole program instantly?

The Scenario

Imagine you are writing a program that uses the value of pi (3.14159) many times. You type this number everywhere in your code manually.

The Problem

Typing the same number repeatedly is slow and easy to mess up. If you want to change the value later, you must find and fix every spot. This causes mistakes and wastes time.

The Solution

Constants let you name a fixed value once and use that name everywhere. If the value changes, you update it in one place only. This makes your code clearer and safer.

Before vs After
Before
double area = 3.14159 * radius * radius;
double circumference = 2 * 3.14159 * radius;
After
const double PI = 3.14159;
double area = PI * radius * radius;
double circumference = 2 * PI * radius;
What It Enables

Constants make your code easier to read, maintain, and less error-prone by giving fixed values meaningful names.

Real Life Example

Think of a recipe that uses a fixed oven temperature. Instead of writing the number everywhere, you write "ovenTemp = 350" once and use that name throughout the recipe instructions.

Key Takeaways

Typing fixed values repeatedly is slow and risky.

Constants let you name and reuse fixed values safely.

Changing a constant updates all uses automatically.