Loading lessons...
Constants
Constants
Some values should never change: the speed of light, the number of days in a week, the tax rate. C lets you lock a value with const.
const
Put const before a declaration and the variable becomes read-only. Any later code that tries to change it gets a compile error:
const int x = 5; // x can never change
x = 10; // ERROR: x is const
- The value is fixed at creation.
- The compiler checks that nothing ever writes to it again.
- It prevents whole classes of "who changed this?" bugs.
Why use constants?
- They make your intent clear: "this is a fixed value, by design".
- They stop accidents.
- A well-named constant reads better:
const double PI = 3.14159;is far clearer than a naked3.14159.
The #define alternative
You may also see the older #define:
#define PI 3.14159
The preprocessor replaces every PI with 3.14159 before compiling. It has no type, so modern style prefers const.
TL;DR
constmakes a variable read-only:const int x = 5;.- Trying to change a const value is a compile error.
- Constants express intent and prevent accidental changes.
#defineis the older, type-less way.