0
0
Cprogramming~3 mins

Why Constants and literals? - 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 calculates the area of a circle multiple times using the value of pi. You type the number 3.14159 everywhere you need it.

The Problem

Typing the same number repeatedly is slow and easy to mess up. If you want to change pi to a more precise value, you must find and replace every instance, risking mistakes and inconsistencies.

The Solution

Constants let you name fixed values once. You write the value of pi just once as a constant, then use its name everywhere. This makes your code easier to read, change, and less error-prone.

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

Constants make your code clearer and safer by giving fixed values meaningful names you can reuse and update easily.

Real Life Example

Think of a recipe that uses a fixed oven temperature. Instead of writing 350°F everywhere, you write a constant named OVEN_TEMP = 350, so if you want to bake at 375°F next time, you change it once.

Key Takeaways

Typing fixed values repeatedly is error-prone and hard to maintain.

Constants let you name and reuse fixed values safely.

This makes your code easier to read, update, and less buggy.