Use const to declare a variable whose value cannot be changed after initialization. Constants make code safer and more readable.
#include <iostream>
using namespace std;
int main() {
const double PI = 3.14159265;
const int MAX_SIZE = 100;
const string GREETING = "Hello";
cout << "PI = " << PI << endl;
cout << "Max Size = " << MAX_SIZE << endl;
cout << GREETING << endl;
// PI = 3.0; // ERROR: cannot assign to const variable
return 0;
}
Output:
PI = 3.14159265
Max Size = 100
Hello
#define Preprocessor Macro
Before C++11, #define was the common way to create constants. It is a preprocessor directive — the compiler replaces every use of the name with the value before compiling.
Prefer const over #define:const is type-safe, respects scope, and shows up in debuggers. Use #define only when necessary for legacy code.
constexpr (C++11)
constexpr means the value is computed at compile time, making programs faster:
constexpr int SQUARE(int x) { return x * x; }
int main() {
constexpr int result = SQUARE(5); // Computed at compile time
cout << result; // Output: 25
}
Exercise
Declare constants for: the number of days in a week (int), the value of gravity (double = 9.8), and the name of your app (string). Print all three.