Learn C · lesson 7 of 60 · about 6 minutes
Constants
Name the numbers in your report with #define and const, so the code explains itself and can't be changed by accident.
What you'll learn
- Declare a const variable
- Define a constant with #define
- Avoid magic numbers
No magic numbers
Your report works out used * 100 / 8192. What's 8192? You know it's the disk's size, but someone reading the code later won't. A number like that is called a magic number. Give it a name instead:
#define DISK_KIB 8192tells the compiler to swap everyDISK_KIBfor8192before compilingconst int RESERVED_KIB = 512;is a variable that can't be changed
Constants are written in CAPITALS so they stand out. If the disk grows, you change one line.
Both kinds
#include <stdio.h>
#define DISK_KIB 8192
int main(void) {
const int RESERVED_KIB = 512;
int used = 2560;
printf("Disk: %d%% full\n", used * 100 / DISK_KIB);
printf("Free: %d KiB\n", DISK_KIB - RESERVED_KIB - used);
return 0;
}Output
Disk: 31% full
Free: 5120 KiBFind and replace
#define isn't really C: it's an instruction to the preprocessor, which runs before the compiler and pastes 8192 wherever it sees DISK_KIB. So a #define line has no type, no = and no ;.
const is a real variable, with a type and a box in memory. The compiler just refuses to let anything change it.
Tip
#define lines don't end with a semicolon. Anything after the name is pasted in, semicolon and all.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.