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;
}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;
}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:
| Literal | Type |
|---|---|
42 | int |
42L, 42LL | long, long long |
42u | unsigned int |
3.5 | double |
3.5f | float |
'x' | a character (char value) |
"text" | a string |
0x1F | int 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
- Write a program that converts 5 kilometres to miles with a constant
KM_PER_MILEof 1.609. - Use
#definefor the size of a class (30) and print how many students fit in 4 classes. - Try to change a
constvariable and read the error.