Course contentsShow
← C
Lesson 768 of 1,21911. The Preprocessor and BuildFree lesson

Defining constants with `#define`

Defining constants with #define

What you'll learn: How to use the preprocessor to give meaningful names to fixed values, making your code easier to read and maintain.

The "Search and Replace" Assistant

Imagine you are writing a long book, and you have a character named "Jonathan." Halfway through, you decide his name should be "John." Instead of scouring every page to change it manually, you use a "Find and Replace" tool.

In C, the preprocessor is that tool. The #define directive tells the computer: "Every time you see this specific word, swap it out for this specific value before you actually start compiling the code."

We call these macros or symbolic constants.

Why use it?

Technically, you could just type the number 3.14159 every time you need to calculate the area of a circle. However, using a constant like PI is better for two reasons:

  1. Readability: radius * radius * PI is much clearer to a human than radius * radius * 3.14159.
  2. Maintainability: If you decide you need more precision (like 3.14159265), you only have to change it in one place at the top of your file, rather than hunting through hundreds of lines of code.

How to write it

A #define statement usually sits at the very top of your file. It follows a simple pattern: #define, then the name (usually in ALL_CAPS), then the value. Notice that there is no equals sign and no semicolon at the end.

#include <stdio.h>

// Defining our constants
#define MAX_PLAYERS 4
#define SERVER_NAME "North_Star"

int main() {
    printf("Welcome to %s!\n", SERVER_NAME);
    printf("The room limit is %d players.\n", MAX_PLAYERS);
    
    return 0;
}

The "Invisible" Step

It is important to remember that #define isn't a variable. It doesn't take up memory while the program is running. Before the compiler even looks at your logic, the preprocessor literally replaces the text MAX_PLAYERS with the digit 4. By the time the program is being built, the names are gone, leaving only the raw values behind.

Key takeaway

Use #define to turn "magic numbers" into descriptive names, making your code easier to update and understand.