Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Constants

Some values must never change while a program runs: the number of days in a week, the value of pi, the maximum number of players. C has two ways to name such values, so the program is easier to read and a typing mistake cannot change them.

const

Put the keyword const before the type, and the variable can only get its value once, when it is declared. Trying to change it later is a compile error.

#include <stdio.h>

int main(void) {
    const int DAYS_PER_WEEK = 7;
    const double PI = 3.14159;
    int weeks = 3;
    printf("%d weeks = %d days\n", weeks, weeks * DAYS_PER_WEEK);
    printf("Circle of radius 2: area %.2f\n", PI * 2 * 2);
    return 0;
}
Output
3 weeks = 21 days
Circle of radius 2: area 12.57

If you add the line DAYS_PER_WEEK = 8;, the compiler stops with an error like cannot assign to variable with const-qualified type. That is exactly what we want: the mistake is found before the program runs.

#define

The preprocessor command #define gives a name to a value. Before compiling, every use of the name is replaced by the value. There is no type, no = and no semicolon.

#include <stdio.h>

#define MAX_PLAYERS 4
#define GREETING "Welcome!"

int main(void) {
    printf("%s Up to %d players can join.\n", GREETING, MAX_PLAYERS);
    return 0;
}
Output
Welcome! Up to 4 players can join.

const variables have a type the compiler checks, so they are usually the better choice inside functions. #define is common for sizes of arrays and settings at the top of a file. The Preprocessor and Macros topic shows more.

Literal values

A value written directly in the code is a literal. Its form decides its type:

LiteralType
42int
42L, 42LLlong, long long
42uunsigned int
3.5double
3.5ffloat
'x'a character (char value)
"text"a string
0x1Fint written in hexadecimal (31)

Naming

By convention, constants are written in UPPER_CASE with underscores, so they stand out from variables. Replace "magic numbers" in your code with named constants: if (age >= ADULT_AGE) explains itself, if (age >= 18) does not say why 18.

Practice exercises

  1. Write a program that converts 5 kilometres to miles with a constant KM_PER_MILE of 1.609.
  2. Use #define for the size of a class (30) and print how many students fit in 4 classes.
  3. Try to change a const variable and read the error.