C++ Constants and Literals β Fixed Values in Your Code
Introduction β What Are Constants and Literals in C++?
In C++, constants and literals represent fixed values that do not change during program execution. Constants are often used to make code more readable, maintainable, and secure by preventing accidental changes to important values.
In this guide, youβll learn:
- What constants and literals are
- Types of literals in C++
- How to define and use constants
- Key differences between
const,#define, and literals
What Are Constants in C++?
A constant is a named value that cannot be modified after its declaration.
Declaring Constants Using const Keyword
const float PI = 3.14159;
const int MAX_USERS = 100;
- Cannot be changed after initialization
- Must be initialized during declaration
What Are Literals?
A literal is a fixed value used directly in the code. It can represent:
- Numbers (
42) - Characters (
'A') - Strings (
"Hello") - Boolean values (
true,false)
Types of Literals in C++
1οΈβ£ Integer Literals
int num = 100;
int hex = 0xFF; // Hexadecimal
int bin = 0b1010; // Binary (C++14+)
2οΈβ£ Floating-point Literals
float pi = 3.14f;
double gravity = 9.8;
3οΈβ£ Character Literals
char grade = 'A';
char newline = '\n';
4οΈβ£ String Literals
string message = "Welcome!";
In C++, string literals like "Hello" are of type const char[].
5οΈβ£ Boolean Literals
bool isOnline = true;
bool isDead = false;
6οΈβ£ Null Pointer Literal (C++11)
int* ptr = nullptr; // Preferred over NULL
Example β Constants & Literals Together
#include <iostream>
using namespace std;
int main() {
const float TAX_RATE = 0.18; // Constant
float price = 100.0; // Literal 100.0
float tax = price * TAX_RATE;
cout << "Tax: " << tax << endl;
return 0;
}
const vs #define for Constants
| Feature | const | #define |
|---|---|---|
| Type-safe | Yes | No |
| Scoped | Respects C++ scoping rules | Global by default |
| Debuggable | Better error messages | No type info during debugging |
| Preferred in C++ | Use const, constexpr, enum | Legacy C macro usage |
Summary β Recap & Next Steps
Key Takeaways:
- Constants are fixed variables defined using
constorconstexpr - Literals are fixed values like
42,'A',3.14, or"text" - Prefer
constover#definefor type safety and maintainability
Real-World Relevance:
Using constants and literals correctly reduces hard-coded values, improves code clarity, and prevents bugs from accidental value changes.
FAQs β C++ Constants and Literals
What is the difference between a constant and a literal?
A constant is a named value (const int max = 10;), while a literal is a raw value (10).
Can I change a const value later?
No. Once declared, a const variable cannot be modified.
Should I use #define or const in C++?
Use const or constexprβthey are type-safe and scoped.
What is a string literal?
A string value enclosed in double quotes, e.g., "Hello".
What is nullptr?
It is a C++11 keyword representing a null pointer value, preferred over NULL.
Share Now :
