CPP Constants

C++ Tutorial

💻 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

const int MAX = 100;

📌 MAX cannot be modified later.


2️⃣ Types of Constants in C++ ⭐⭐

🔹 1. Literal Constants

Values written directly in code.

10 // integer constant
3.14 // floating constant
'A' // character constant
"Hello" // string constant
true // boolean constant

🔹 2. const Keyword Constants ⭐

const int x = 10;
const float PI = 3.14;

❌ Invalid:

x = 20; // error

🔹 3. #define Constants (Macro) ⭐⭐

#define PI 3.14

📌 No data type
📌 Preprocessor replaces value before compilation

❌ Not recommended in modern C++ (use const instead)


🔹 4. constexpr Constants (C++11+) ⭐⭐⭐

constexpr int size = 50;

📌 Value must be known at compile time
📌 Faster & safer than #define


3️⃣ Constant Variable Example ⭐


 

Output

7

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 ⭐⭐

const int a = 10;
const int b = a + 5;

✔ 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

You may also like...