Thuta Learning
C
BasicProgrammingBeginner

Constants

CLesson 825 min

What you'll walk away with

  • Name magic numbers with a const variable, a #define macro or an enum constant
  • Explain why a const int cannot be a case label or a file-scope array size in C
  • Write macros with parentheses and without a trailing semicolon, and know why
  • Choose between const, #define and enum for a given situation

Explain it simply

Explain it simply

A constant gives a name to a value that should never change while the program runs: 60 minutes per hour, PI, the maximum seats in a room, a tax rate. Writing MINUTES_PER_HOUR instead of a bare 60 tells every reader what the number means at a glance.

The second benefit is that the value lives in exactly one place. When the tax rate goes up, you edit one definition and every use updates automatically. C offers three ways to write a constant, and each has its own strengths.

Problem → Why → Solution

The problem: a tax rate that drifted apart

Imagine an invoice program that writes the tax rate 0.07 directly in three places. When the rate changes to 0.08, one developer updates only the refund code. The program compiles without a single warning, and customers now get one rate on invoices and another on refunds. Worse, the next reader cannot tell whether 0.07 is a tax, a discount or a commission.

invoice.c
double subtotal = 120.0;
double tax = subtotal * 0.07;               /* what is 0.07? */
printf("Tax: %.2f\n", tax);

/* ... 200 lines later ... */
double total = subtotal + subtotal * 0.07;  /* same number, copied */

/* ... in the refund code, someone already changed it ... */
double refund_tax = subtotal * 0.08;        /* now the copies disagree */

Why can the compiler not help here?

To the compiler, 0.07 and 0.08 are both perfectly valid double literals; it has no idea they were meant to be the same. Only when the value lives under one name such as TAX_RATE is there a single place to change, and the copies can no longer disagree. The name also turns the code into its own documentation.

Core concept: const, #define and enum

const makes a variable read-only. const int MINUTES_PER_HOUR = 60; has a type (int), a scope (it is visible only in the block where it is declared), and a name the debugger can show. Try to assign to it and GCC refuses with error: assignment of read-only variable 'MINUTES_PER_HOUR'. In C, however (unlike C++), a const variable is not an "integer constant expression", so it cannot be a switch case label or the size of a file-scope array.

#define MAX_SEATS 40 is not a variable at all. Before compilation, the preprocessor replaces every MAX_SEATS token with 40: plain find-and-replace. It has no type and no scope (it applies from the #define to the end of the file), but it works anywhere a literal 40 would. Because the text is pasted verbatim, a macro holding an expression must be wrapped in parentheses and must not end with a semicolon.

enum { DAYS_PER_WEEK = 7 }; creates a named int constant. It is a true integer constant expression, so case labels and array sizes accept it, and unlike a macro it follows the normal scope rules for identifiers. Its limit is that it only holds integers: a double such as 3.14159 cannot go into an enum.

A practical rule: const for non-integer values such as doubles and whenever you want type checking; enum for related integer codes and sizes; #define for preprocessor work such as conditional compilation, or for values shared project-wide through header files. Writing constant names in UPPER_SNAKE_CASE is a widely used convention that makes them stand out from variables. C23 adds constexpr for objects, but check your compiler's support first.

FormType and scopecase label / file-scope array size
const int LIMIT = 40;typed int, block scopenot allowed in C
#define LIMIT 40untyped text, to end of fileallowed
enum { LIMIT = 40 };typed int, normal scopeallowed
Mental model: who substitutes the value?
  1. #define: preprocessor pastes text
  2. enum: compiler knows an int constant
  3. const: a read-only variable in memory
  4. Compiler blocks writes to a const

Need the value at compile time (case labels, array sizes)? Use enum or #define. Need a typed read-only value? Use const.

General pattern

c
#define NAME value                /* no type, no = and no ; */
#define NAME_EXPR (a + b)          /* expressions in parentheses */

enum { CONSTANT_A = 1, CONSTANT_B = 2 };   /* named int constants */

int main(void) {
  const type NAME = value;         /* typed, read-only, scoped */
  return 0;
}

A #define has no = and no semicolon, and an expression goes in parentheses. An enum can declare several comma-separated int constants at once. A const is an ordinary declaration with const in front, and it must get its value where it is declared.

Example: all three kinds of constant at work

This program works out numbers for a tiny booking system. The seat limit is a #define, the days per week an enum, and the time unit and PI are const. Notice that the calculations contain no unexplained numbers: every rule has a name, and the remaining 3 and 2 are inputs to this one calculation.

constants.c
#include <stdio.h>

#define MAX_SEATS 40
enum { DAYS_PER_WEEK = 7 };

int main(void) {
  const int MINUTES_PER_HOUR = 60;
  const double PI = 3.14159;
  int booked_today = 33;

  printf("Minutes in 3 hours: %d\n", 3 * MINUTES_PER_HOUR);
  printf("PI: %.2f\n", PI);
  printf("Circle area (r = 2): %.2f\n", PI * 2 * 2);
  printf("Seats left: %d of %d\n", MAX_SEATS - booked_today, MAX_SEATS);
  printf("Seats per week: %d\n", MAX_SEATS * DAYS_PER_WEEK);
  return 0;
}

Code breakdown

  1. Line 3#define MAX_SEATS 40

    Before compilation every MAX_SEATS token becomes 40. Note: no = sign and no semicolon.

  2. Line 4enum { DAYS_PER_WEEK = 7 };

    An unnamed enum declaring one int constant. It ties 7 to a name and is also usable as a case label or an array size.

  3. Lines 7-8const double PI = 3.14159;

    const variables have a type and are visible only inside main. PI = 3; would be a compile error. PI is a double, so enum is not an option and const is the natural fit.

  4. Line 13PI * 2 * 2

    The area of a circle with radius 2 (pi r squared). 3.14159 x 4 = 12.56636, which %.2f rounds to 12.57.

  5. Line 15MAX_SEATS * DAYS_PER_WEEK

    After preprocessing this reads 40 * DAYS_PER_WEEK, and the compiler computes 280. If the seat limit changes, only line 3 needs editing.

You should see
Minutes in 3 hours: 180
PI: 3.14
Circle area (r = 2): 12.57
Seats left: 7 of 40
Seats per week: 280

A macro is only pasted text

The preprocessor knows no maths; it only pastes text. After #define BAD_TOTAL 2 + 3, the expression BAD_TOTAL * 10 becomes 2 + 3 * 10, and because * binds tighter than +, the result is 32, not 50. GOOD_TOTAL, wrapped in parentheses, becomes (2 + 3) * 10 and gives the expected 50. Run it and see for yourself.

macro_parens.c
#include <stdio.h>

#define BAD_TOTAL 2 + 3
#define GOOD_TOTAL (2 + 3)

int main(void) {
  printf("BAD_TOTAL * 10 = %d\n", BAD_TOTAL * 10);
  printf("GOOD_TOTAL * 10 = %d\n", GOOD_TOTAL * 10);
  return 0;
}

A semicolon gets pasted the same way. With #define MAX_SEATS 40; the line int left = MAX_SEATS - 7; turns into int left = 40; - 7; and it still compiles: GCC only says warning: statement with no effect, and left is 40 instead of 33. Never end a macro definition with a semicolon.

In real projects

Where this shows up in real projects

Large C projects usually collect configuration limits as #defines in a header file, such as #define BUFFER_SIZE 256 or #define MAX_CLIENTS 64. Every .c file that includes the header sees the same value, and if the header wraps the definition in #ifndef MAX_CLIENTS, the build system can override it with a flag like gcc -DMAX_CLIENTS=128. Related codes, such as HTTP statuses, error codes or menu options, are grouped in an enum and then used as case labels in a switch.

Scientific and engineering code tends to write physical constants as const double, because they keep a type and show up in the debugger. One trap is M_PI: it is a POSIX extension rather than part of ISO C, so compiling with gcc -std=c17 can fail with error: 'M_PI' undeclared. That is why many projects define their own PI constant once and reuse it everywhere.

Common mistakes

Common mistakes

1. Ending a macro with a semicolon

#define MAX_SEATS 40; pastes the ; into every use. In some places that is a syntax error; in a line like int left = MAX_SEATS - 7; it compiles with only a warning and silently gives the wrong value.

2. Leaving an expression macro unparenthesised

After #define TOTAL 2 + 3, the expression TOTAL * 10 is 32, not 50. Wrap every expression macro in outer parentheses, as in (2 + 3), or use a const variable instead.

3. Treating a const int as a compile-time constant

With const int CODE = 2;, writing case CODE: makes GCC report error: case label does not reduce to an integer constant, and int table[SIZE]; at file scope gives error: variably modified 'table' at file scope. Use enum or #define in those places.

Best practices

Best practices

  • Name every number that carries meaning (a rate, a limit, a unit); self-explanatory values like 0 and 1 can stay bare.
  • Reach for const for doubles and enum for related integer codes before #define.
  • If you use #define, parenthesise every expression and never add a semicolon.
  • Write constants in UPPER_SNAKE_CASE and put the unit in the name (TIMEOUT_MS, MAX_WEIGHT_KG).

Mini challenge

Mini challenge: a parking fee calculator

A car park gives the first 15 minutes free and charges $1.50 per hour for the rest. Compute the fee for a car parked for 135 minutes without a single magic number in the calculation.

  • Write the free minutes (15) as a #define
  • Write the minutes per hour (60) as an enum constant
  • Write the hourly rate (1.50) as a const double
  • Print the billable hours and the fee with 2 decimals
parking.c
#include <stdio.h>

/* TODO: #define for the free minutes */
/* TODO: enum constant for minutes per hour */

int main(void) {
  /* TODO: const double for the hourly rate */
  int parked_minutes = 135;

  /* TODO: billable minutes, billable hours (keep the fraction), fee */

  /* TODO: print parked minutes, billable hours and the fee */
  return 0;
}

Expected: For 135 minutes the output is: Parked: 135 min (15 free) Billable hours: 2.00 Fee: $3.00

Show hint

Converting billable minutes to hours is int / enum, which would drop the fraction. Add a (double) cast.

Show solution
parking.c
#include <stdio.h>

#define FREE_MINUTES 15
enum { MINUTES_PER_HOUR = 60 };

int main(void) {
  const double RATE_PER_HOUR = 1.50;
  int parked_minutes = 135;

  int billable_minutes = parked_minutes - FREE_MINUTES;
  double billable_hours = (double)billable_minutes / MINUTES_PER_HOUR;
  double fee = billable_hours * RATE_PER_HOUR;

  printf("Parked: %d min (%d free)\n", parked_minutes, FREE_MINUTES);
  printf("Billable hours: %.2f\n", billable_hours);
  printf("Fee: $%.2f\n", fee);
  return 0;
}

Quick quiz 1 / 3

After #define SIZE 4 + 1, what does printf("%d\n", SIZE * 2); print?

Quick quiz 2 / 3

With const int LIMIT = 10; at file scope, which line is a compile error in C17?

Quick quiz 3 / 3

You need four order status codes (PENDING, PAID, SHIPPED, CANCELLED) to use as switch case labels. Which fits best?

What to remember

  • Naming magic numbers explains them and leaves a single place to change.
  • const gives a typed, scoped, read-only variable, but in C it cannot be a case label or a file-scope array size.
  • #define is the preprocessor's text substitution: parenthesise expressions and never add a semicolon.
  • enum gives int constants that are integer constant expressions, ideal for codes and sizes.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Constants | Thuta Learning