A constant is a variable whose value cannot change once it is set. Why would you want that? Because some values should never change — the value of PI, the number of months in a year, the tax rate. Using constants makes your code safer and easier to read. If someone tries to change a constant later, the compiler will stop them.
The const Keyword
The most common way to create a constant in C++ is with the const keyword.
Just put const before the type when you declare the variable. You must
give it a value right away because you cannot change it later.
The #define Directive
There is also an older way using #define. It is a preprocessor directive
that replaces every occurrence of a name with a value before compilation. It does not
have a type and does not follow the same rules as const. These days,
const is the preferred approach, but you will still see #define
in older code.
#include <iostream>
using namespace std;
const double PI = 3.14159;
#define DAYS_IN_WEEK 7
int main() {
double radius = 5.0;
double area = PI * radius * radius;
cout << "Radius: " << radius << endl;
cout << "Area: " << area << endl;
cout << "Days in a week: " << DAYS_IN_WEEK;
// PI = 3.0; // This would cause an error!
return 0;
}
Notice there is no semicolon after #define — it is a preprocessor directive,
not a statement. And unlike const, #define does not create
an actual variable. It is more like a find-and-replace that happens before your code
is compiled.