CPP Constants
💻 C++ Constants (CPP Constants) – Complete Beginner to Interview Guide
In CPP Constants are values that cannot be changed during program execution.
They help make programs safe, readable, and error-free.
1️⃣ What is a Constant? ⭐
A constant is a fixed value whose value remains the same throughout the program.
Example
📌 MAX cannot be modified later.
2️⃣ Types of Constants in C++ ⭐⭐
🔹 1. Literal Constants
Values written directly in code.
🔹 2. const Keyword Constants ⭐
❌ Invalid:
🔹 3. #define Constants (Macro) ⭐⭐
📌 No data type
📌 Preprocessor replaces value before compilation
❌ Not recommended in modern C++ (use const instead)
🔹 4. constexpr Constants (C++11+) ⭐⭐⭐
📌 Value must be known at compile time
📌 Faster & safer than #define
3️⃣ Constant Variable Example ⭐
Output
4️⃣ Difference: Variable vs Constant ⭐⭐
| Variable | Constant |
|---|---|
| Value can change | Value cannot change |
int x = 10; |
const int x = 10; |
| Less safe | More safe |
5️⃣ Constant Expressions ⭐⭐
✔ Allowed if value is fixed.
6️⃣ Common Mistakes ❌
❌ Changing constant value
❌ Forgetting initialization
❌ Using #define unnecessarily
❌ Confusing const and constexpr
📌 Interview Questions (CPP Constants)
Q1. What is a constant in C++?
👉 A fixed value that cannot be change
Q2. Difference between const and #define?
👉 const has type safety, #define does not
Q3. What is constexpr?
👉 Compile-time constant
Q4. Can a constant be uninitialized?
👉 ❌ No
✅ Summary
✔ Constants store fixed values
✔ Improve safety and readability
✔ const is preferred
✔ constexpr for compile-time values
✔ Constants cannot be modifie
