Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 135 ยท Variables and Types

Constants: const, #define, enum and constexpr

Learn every way to name a fixed value in C - literals, const variables, #define macros, enum constants and C23 constexpr - how they differ, and when to use each.

Programs are full of values that never change: the number of days in a week, the size of a buffer, the maximum number of players, a tax rate, the value of ฯ€. You could type the number everywhere you need it, but then nobody knows what 86400 or 0.19 means, and changing it later means hunting through every file. The fix is to give the value a name.

C offers several ways to do that, and they're not interchangeable: a const variable, a #define macro, an enum constant and, since C23, a constexpr object. Each has different rules about types, scope and where it can be used. This lesson starts with literals, the raw constant values, then compares the four naming tools and ends with clear recommendations.

Literals: constants written directly

A literal is a value written directly in the source code. Every literal has a type, determined by how you write it:

Literal Type Notes
42, 0x2A, 052, 0b101010 int Decimal, hex, octal, binary (C23); bigger values get a wider type
42u, 42L, 42LL, 42ULL unsigned int, long, long long, unsigned long long Suffixes choose the type
3.14, 1e-3 double No suffix means double
3.14f, 3.14L float, long double
'A', '\n' int Character literals are int in C
"hello" char[6] Includes the terminating '\0'; must not be modified
true, false bool (C23) int macros in older standards
nullptr nullptr_t (C23) The null pointer constant

The details of each kind are in Integer Types, Floating-Point Numbers, Characters and Booleans.

String literals deserve a special warning. They're stored in memory that's typically read-only, and modifying one is undefined behavior, even though their type is char[] rather than const char[] for historical reasons. Point to them with const char *:

C
const char *greeting = "Hello";   // good: the compiler stops accidental writes
char *risky = "Hello";            // compiles, but risky[0] = 'J' is undefined behavior
char copy[] = "Hello";            // an array initialized with a copy: safe to modify

Magic numbers and why to name them

A magic number is an unexplained literal in the middle of code. Compare these two lines:

C
if (elapsed > 86400) { /* ... */ }
if (elapsed > SECONDS_PER_DAY) { /* ... */ }

The second one documents itself, and if the value ever changes, you change it in one place. Small, obvious values like 0, 1, 2 in n / 2 or i + 1 don't need names; values with a meaning do.

const variables

Adding const to a variable declaration makes it read-only: you must initialize it, and the compiler rejects any later assignment. It's a normal variable in every other way: it has a type, it obeys scope rules, it has an address, and a debugger can show it.

C const variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

const char *const shop_name uses const twice: the first makes the characters read-only, the second makes the pointer itself read-only. That distinction gets a whole lesson, const and Pointers.

If you try to change a const variable, the program doesn't compile. This example fails on purpose:

C Assigning to a const fails

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC reports error: assignment of read-only variable 'days_per_week'. That's the whole point: mistakes are caught at compile time. (Casting the const away with a pointer and writing through it compiles, but it's undefined behavior. Don't.)

The catch: const is not a compile-time constant

In C, unlike C++, a const variable is not a constant expression. The standard says it's just a variable you promised not to change. So it can't be used where the language requires a value known at compile time:

C
const int SIZE = 3;
int table[SIZE];      // at file scope: error: variably modified 'table' at file scope

int main(void) {
    int local[SIZE];  // compiles, but it's a variable-length array, not a fixed one
}

Places that require true constant expressions include the size of arrays outside functions, case labels, bit-field widths, initializers of static variables, and static_assert. GCC accepts const variables in some of those places, such as case labels, as an extension (with -pedantic it warns "case label is not an integer constant expression"), but other compilers reject them, so portable code uses enum, #define or C23 constexpr there.

#define constants

The classic C way to name a constant is a macro, created with the preprocessor directive #define:

C
#define BUFFER_SIZE 256
#define PI 3.14159265358979323846
#define APP_NAME "TinyEdit"

Before compilation, the preprocessor replaces every occurrence of the name with the text after it. The compiler never sees BUFFER_SIZE, only 256. That's why macros work everywhere a literal works, including array sizes and case labels, and why they've been used for constants since the beginning of C. The standard library is full of them: INT_MAX, EOF, NULL, BUFSIZ.

But plain text substitution has costs:

  • No type. PI is just characters; its type is whatever the literal turns out to be.
  • No scope. A macro is visible from its #define to the end of the file, inside every function, and it can clash with names in other headers.
  • No debugger symbol. Debuggers usually show 256, not BUFFER_SIZE.
  • Precedence surprises. If the replacement is an expression, always wrap it in parentheses:
C Why macro constants need parentheses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

100 / AREA_BAD becomes 100 / 10 * 5, which is (100 / 10) * 5 = 50, while 100 / AREA_GOOD is 100 / (10 * 5) = 2. Likewise TOTAL_BAD * 10 becomes 2 + 3 * 10 = 32, not 50. Macros, including their many other traps, are covered in The Preprocessor and Macros.

Tip: By convention, macro names are written in ALL_CAPS so readers know text substitution is happening. Don't end a #define with a semicolon: #define SIZE 10; pastes the semicolon too, and int a[SIZE]; becomes int a[10;];.

enum constants

An enumeration defines a set of named integer constants. Each name gets a value, counting up from 0 unless you set it:

C enum constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Enum constants are true integer constant expressions, so they work for array sizes and case labels, and unlike macros they follow normal scope rules and show up by name in debuggers. Their limitation is the type: an enum constant is an int (C23 lets you choose another integer type with enum : type), so it can't hold a double or a string. The anonymous enum { MAX_PLAYERS = 4 }; pattern is a well-known trick for integer constants in pre-C23 code. Enumerations covers enums as types in full.

constexpr (C23)

C23 borrowed constexpr from C++ for objects. A constexpr variable is a real compile-time constant with a type and a scope: everything you wanted from const, plus the ability to be used in constant expressions:

C constexpr constants in C23

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C23's constexpr is deliberately stricter than C++'s:

  • It applies only to objects (variables), not functions.
  • The initializer must be a constant expression. constexpr int m = n * 2; with a variable n fails with error: initializer element is not constant.
  • The value must fit the type exactly. constexpr unsigned char small = 300; is an error, and so is constexpr float f = 0.1;, because the double value 0.1 can't be represented exactly as a float. Write 0.1f.
  • Allowed types are arithmetic types, pointers (only null), and structs/arrays of those; no volatile, no atomics.

constexpr needs a C23 compiler (GCC 13+, Clang 19+). If your code must build with older compilers, use enum for integers and #define (or static const) for the rest.

Which one should you use?

Need Best choice (C23) Portable choice (C99โ€“C17)
Integer constant for array sizes or case labels constexpr int enum { N = 10 }; or #define N 10
Floating-point or string constant constexpr double, static const char[] static const double, #define
A value computed at run time that must not change afterward const const
A function parameter you won't modify through a pointer const T * const T *
Related named values (states, colors, days) enum enum
Conditional compilation (#if) #define #define

The short version: use const to protect values from modification, constexpr (or enum in older code) for true compile-time constants, enum for related sets of names, and #define only where the preprocessor itself needs the value, such as #if checks and header-wide configuration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. #define DOUBLE_IT 2 * 3 What does printf("%d", 12 / DOUBLE_IT); print?

    The macro is pasted as text, so the expression is 12 / 2 * 3, which evaluates left to right as 6 * 3 = 18. Wrapping the replacement in parentheses fixes it.
  2. 2. In C17, which of these can be used as the size of an array declared at file scope?

    Enum constants are integer constant expressions. A const variable is not a constant expression in C, so using it at file scope gives a variably modified array error.
  3. 3. Why does constexpr float ratio = 0.1; fail in C23?

    C23 constexpr requires the initializer's value to be exactly representable in the object's type. 0.1 as a double differs from the nearest float, so you must write 0.1f.
  4. 4. What happens when you modify a string literal through char *s = "abc"; s[0] = 'x';?

    String literals must not be modified. The code compiles because the literal's type is char[], but writing to it is undefined behavior. Use char s[] = "abc"; for a modifiable copy.
  5. 5. Which tool is visible only from its definition to the end of the file, ignoring function and block scopes?

    Macros are handled by the preprocessor as plain text substitution, before the compiler applies scope rules. The other three are ordinary identifiers with normal scope.

Summary

  • Literals have types set by their spelling and suffix; string literals must never be modified, so point to them with const char *.
  • Name meaningful values instead of scattering magic numbers.
  • const makes a variable read-only, but in C it isn't a compile-time constant (no file-scope array sizes, no portable case labels).
  • #define is untyped text substitution that works everywhere; wrap expressions in parentheses and use ALL_CAPS.
  • enum constants are true integer constants with normal scope.
  • C23 constexpr gives typed, scoped compile-time constants; values must fit their type exactly.

Next: Type Conversions and Casts, where you'll learn what happens when values of different types meet.