C Constants

Sometimes you have a value in your program that should never change while the program runs, like the number of days in a week or the value of Pi. In C, you can protect such a value by turning it into a constant. Once a value is marked as constant, the compiler will stop you from accidentally changing it later.

Creating Constants

To create a constant, place the keyword const in front of a normal variable declaration. This tells C that the value is read-only. You must give the constant a value at the moment you declare it, because you will not be allowed to assign to it afterwards.

A simple constant

#include <stdio.h>

int main() {
  const int MIN_AGE = 18;
  printf("You must be at least %d years old.\n", MIN_AGE);
  return 0;
}

The program above prints: You must be at least 18 years old. The value 18 is now locked. If you try to change it later in the program, the code will not compile.

Note: It is a common habit among C programmers to write constant names in UPPERCASE letters, like MIN_AGE or PI. This is not required by the language, but it makes constants easy to spot in your code.

You Cannot Change a Constant

The whole point of a constant is safety. If someone (including future you) tries to overwrite the value by mistake, the compiler catches the error instead of letting a bug slip through.

This will cause an error

#include <stdio.h>

int main() {
  const int SPEED_LIMIT = 60;
  // SPEED_LIMIT = 80;  // Error: cannot assign to a const
  printf("The speed limit is %d.\n", SPEED_LIMIT);
  return 0;
}

const vs #define

There is another way to create fixed values in C using the #define directive, which is handled before the code is compiled. Both approaches are common, but they work differently. The table below sums up the main points.

Featureconst#define
Keywordconst int PI_INT = 3;#define PI_INT 3
Has a data typeYes, checked by the compilerNo, it is a plain text replacement
Uses memoryUsually stored like a variableReplaced directly in the code
Best forTyped, scoped valuesSimple constants and settings
Note: When you use #define, you do not write an equals sign or a semicolon: #define MAX 100 is correct, while #define MAX = 100; is a common beginner mistake.

Exercise: C Constants

What does the #define directive actually do with a constant like MAX?