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

Why use constants?

Why use constants?

What you'll learn: How the const keyword makes your code safer, easier to read, and more reliable by preventing accidental changes.

Up to this point, we have treated variables like whiteboards—you write a value down, and you can erase and change it whenever you like. However, in the real world, some values never change. A week always has 7 days. The speed of light is fixed. In your code, these are "Constants."

Safety through immutability

Imagine you are building a banking app. You define a variable for the INTEREST_RATE. If you leave it as a regular variable, a tired programmer might accidentally write a line of code later that changes that rate to 500%, crashing the economy of your app.

By adding the const keyword, you are telling the C compiler: "This value is set in stone. If any part of the program tries to change it, stop everything and throw an error." This prevents bugs before your program even runs.

Code that explains itself

Constants also replace "Magic Numbers"—random digits scattered through your code that have no context. Which of these is easier to understand?

  1. total = days * 86400;
  2. total = days * SECONDS_PER_DAY;

The second version is self-documenting. If you ever need to change a fixed value (like a version number or a tax rate), you only have to change it in one place at the top of your file, rather than hunting through thousands of lines of code.

How it looks in code

You create a constant by putting the word const before the data type. By convention, programmers usually write constant names in ALL_CAPS to distinguish them from regular variables.

#include <stdio.h>

int main() {
    // This value cannot be changed after it is set
    const int DAYS_IN_WEEK = 7;
    const float PI = 3.14159;

    printf("There are %d days in a week.\n", DAYS_IN_WEEK);

    // The following line would cause a compiler error:
    // DAYS_IN_WEEK = 8; 

    return 0;
}

Key takeaway

Use const for any value that shouldn't change during your program’s execution to prevent accidental bugs and make your code easier for humans to read.