Course contentsShow
← C
Lesson 118 of 1,2192. Variables and TypesFree lesson

Literal vs. Symbolic constants

Literal vs. Symbolic constants

What you'll learn: You'll discover the difference between "magic numbers" typed directly into code and named constants that make your programs easier to read and maintain.

The "Magic Number" Problem

Imagine you are writing a program to calculate the total price of items in a shopping cart. To calculate tax, you multiply the total by 0.07.

In C, the number 0.07 is a Literal Constant. It is "literal" because its value is exactly what it looks like on the screen. While this works, literals can be mysterious. If a new programmer looks at your code and sees total * 0.07, they might wonder: "Is this a tax rate? A discount? A shipping fee?" Because the number has no name, it is often called a "magic number"—it does something important, but its purpose is hidden.

Giving Values a Name

A Symbolic Constant is a way to give that literal value a meaningful name. Instead of using 0.07 everywhere, you create a symbol like SALES_TAX_RATE to represent it.

Think of it like a label on a jar. Instead of tasting the white powder inside every time you need to bake (the literal), you just look for the label that says "Sugar" (the symbolic constant).

How it looks in code

In C, we often use the const keyword to create these symbolic constants. This tells the compiler that the value is "read-only" and cannot be changed while the program is running.

#include <stdio.h>

int main() {
    // 0.07 is a Literal Constant (hard to understand)
    // SALES_TAX_RATE is a Symbolic Constant (easy to understand)
    const float SALES_TAX_RATE = 0.07;
    
    float itemPrice = 100.00;
    float taxTotal = itemPrice * SALES_TAX_RATE;

    printf("The tax is: $%.2f", taxTotal);
    
    return 0;
}

Why bother?

Using symbolic constants offers two major benefits:

  1. Readability: itemPrice * SALES_TAX_RATE reads like a human sentence.
  2. Maintainability: If the tax rate changes to 0.08, you only have to change it in one place (where the constant is defined) rather than searching through thousands of lines of code to find every 0.07.

Key takeaway

Literal constants are raw values typed directly into code, while symbolic constants use names to make those values meaningful and easy to update.