C ยท Chapter 9 of 45

C Constants

A constant is a value that cannot change once it's set. In C you can create constants using the const keyword or with the #define preprocessor directive.

Using constants instead of hardcoded 'magic numbers' scattered through your code makes programs easier to read, maintain and update.

Syntax
const type NAME = value;
#define NAME value

const keyword

Placing const before a type declaration makes that variable read-only after initialization. Any attempt to reassign it causes a compile error.

#define macro

#define creates a preprocessor macro that textually replaces every occurrence of the name with its value before compilation, and does not use memory like a variable.

Example 1 (c)
#include <stdio.h>

int main() {
  const float PI = 3.14159f;
  printf("%.2f\n", PI);
  return 0;
}
Output
3.14

PI is declared as a const, so it cannot be changed later in the program.

Example 2 (c)
#include <stdio.h>
#define MAX 100

int main() {
  printf("Max is %d\n", MAX);
  return 0;
}
Output
Max is 100

#define MAX 100 replaces every occurrence of MAX with 100 before compiling.

Key points

  • const makes a typed variable read-only.
  • #define creates a preprocessor text-substitution macro.
  • Constants improve readability and prevent accidental changes.
  • By convention, macro constants are written in UPPERCASE.
๐Ÿ’ก Note: Prefer const for typed, scoped constants and reserve #define for simple text substitutions or header guards.

๐Ÿ“ Quick Quiz

1. Which keyword creates a typed read-only variable?

2. What does #define do?

3. By convention, macro constant names are written in: