📌 C++ Constants – Create Fixed Values in C++
Constants are like permanent stickers on your variables — once assigned, their value can’t change! 🔒
In C++, there are two common ways to define constants:
constkeyword#definepreprocessor directive
🔍 Method 1: Using const
The const keyword is used to define a constant variable whose value cannot be changed later.
#include <iostream>
using namespace std;
int main() {
const int DAYS_IN_WEEK = 7;
cout << "There are " << DAYS_IN_WEEK << " days in a week." << endl;
// DAYS_IN_WEEK = 8; // ❌ This will cause a compile-time error
return 0;
}
⚙️ Method 2: Using #define
#define is a preprocessor macro used to define constants before compilation begins.
#include <iostream>
#define PI 3.14159
using namespace std;
int main() {
double radius = 5.0;
double area = PI * radius * radius;
cout << "Area of circle: " << area << endl;
return 0;
}
📘 Difference Between const and #define
constis type-safe and scoped (preferred in C++)#defineis a text replacement before compilation (older style)
🧠 Remember:
- Use
constfor safer and modern C++ code - Constants make your code more readable and bug-resistant
- Once a constant is defined, don’t even think about changing it! 😤