C Constants: A Beginner’s Guide

In C programming, constants are fixed values that do not change during the execution of a program. They make your code more readable, more secure, and easier to maintain.

Why Use Constants?

Prevent accidental modification of values

Make code more meaningful (e.g., PI instead of 3.14)

Improve readability and maintainability

Types of Constants in C

Literal Constants

These are actual fixed values like:

10, 3.14, 'A', "Hello"

Symbolic Constants

Created using either:

  • #define

  • const keyword

Using #define to Declare Constants

const int MAX = 100;
  • Has a data type

  • Can be used in functions or globally

  • Compiler prevents modification

Example:

#include <stdio.h>

int main() {
    const int maxUsers = 50;
    printf("Max Users: %d\n", maxUsers);

    // maxUsers = 100; // ❌ Error: cannot modify a const variable
    return 0;
}

Differences Between #define and const

Feature#defineconst
Data TypeNoYes
ScopeGlobalRespect C scope rules
Compiler CheckNoYes
Debugging HelpLimitedMore accurate error info

Best Practices for Constants

Use UPPERCASE for constant names (e.g., MAX_LIMIT)

Use const when a data type or scope is needed

 Group all constants at the top of your file

Avoid using magic numbers (e.g., use PI instead of 3.14 directly)

Common Mistakes to Avoid

MistakeFix
Modifying a const variableRemove modification or use a non-const
Using undeclared constantsDeclare before use
Using wrong data type with constMatch the type to the intended value