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

Defining constants with `#define`

Defining constants with #define

What you'll learn: How to use the preprocessor to give permanent names to fixed values in your code.

The "Find and Replace" trick

Imagine you are writing a recipe for a massive wedding cake. Throughout the instructions, you mention "30 eggs." If the guest list grows and you suddenly need 40 eggs, you have to hunt through every page to change the number, risking a mistake that ruins the cake.

In C, we solve this using #define. This is a command for the preprocessor—a program that looks at your code just before it is compiled. It acts like a global "Find and Replace" tool. You tell it: "Every time you see the word MAX_PLAYERS, replace it with the number 10."

How to write a definition

You place these definitions at the very top of your file, outside of any functions. The syntax looks like this:

#include <stdio.h>

#define PI 3.14159
#define GOLDEN_RATIO 1.618
#define GAME_TITLE "Space Explorer"

int main() {
    printf("Welcome to %s\n", GAME_TITLE);
    printf("The value of PI is approximately %f\n", PI);
    return 0;
}

Notice a few specific rules here:

  1. No equals sign: We aren't assigning a variable; we are defining a substitution.
  2. No semicolon: Since this isn't a standard C statement, you don't end it with ;.
  3. UPPERCASE names: By convention, programmers use all caps for #define. This makes it obvious to anyone reading your code that the value is a constant and cannot be changed while the program is running.

Why use this instead of numbers?

Using #define makes your code "self-documenting." If a teammate sees the number 86400 in your code, they might be confused. If they see SECONDS_IN_A_DAY, they understand instantly.

Furthermore, because the preprocessor swaps the names for the actual values before the code even runs, these constants don't take up any memory as variables do. They are baked directly into the logic of your program, making them efficient and unchangeable.

Key takeaway

Use #define NAME VALUE at the top of your code to create easy-to-read, unchangeable labels for fixed numbers or text.