const int maxUsers = 100;C++ Constants and Literals: Fixed Values and Literal Forms
Direct Answer & Core Concept
Constants and literals are fundamental parts of C++ programming. A constant represents a value that should not be changed after it has been defined, while a literal is a value written directly in C++ source code.
For example:
Here, maxUsers is a constant variable, while 100 is an integer literal.
C++ supports many literal forms, including integer, floating-point, character, string, Boolean, null pointer, and user-defined literals.
Understanding the difference between constants and literals helps you write clearer, safer, and more predictable C++ programs.
Detailed Explanation & Mechanics
What Are Constants in C++?
A constant is a value that cannot be modified after initialization.
The most common way to create a constant is with the const keyword:
const int daysInWeek = 7;After this declaration, you cannot change the value:
daysInWeek = 8; // ErrorConstants are useful for values that should remain unchanged throughout a program.
Examples include:
Maximum limits
Mathematical values
Configuration values
Conversion factors
Fixed application settings
Array sizes in appropriate contexts
Error codes
Protocol values
What Is a Literal in C++?
A literal is a value that appears directly in source code.
Examples:
100
3.14
'A'
"Hello"
true
nullptrThese are all literals.
For example:
int age = 35;In this statement:
ageis a variable.35is an integer literal.
Another example:
const double pi = 3.141592653589793;Here:
piis a constant object.3.141592653589793is a floating-point literal.
Constants vs Literals
Constants and literals are related, but they are not the same thing.
| Feature | Constant | Literal |
|---|---|---|
| Meaning | A value that cannot be modified through that constant object | A value written directly in source code |
| Has a name? | Usually yes | Usually no |
| Example | const int max = 100; | 100 |
| Can be reused by name? | Yes | You can repeat the literal, but it has no variable name |
| Example type | Constant object | Integer, floating-point, character, string, Boolean, etc. |
Consider:
const int maxScore = 100;maxScore is a named constant.
100 is a literal.
Why Use Constants?
Constants make programs easier to understand and maintain.
Instead of writing:
double price = amount * 0.18;
double tax = subtotal * 0.18;you can define:
const double taxRate = 0.18;
double price = amount * taxRate;
double tax = subtotal * taxRate;Now the purpose of 0.18 is clear.
If the value needs to change later, you only update one declaration.
The const Keyword
The const keyword tells the compiler that an object should not be modified through that declaration.
Example:
const int maxAttempts = 3;
std::cout << maxAttempts;Trying to modify it:
maxAttempts = 5;produces a compilation error.
Declaring Multiple Constants
You can declare several constants separately:
const int minAge = 18;
const int maxAge = 100;
const double interestRate = 7.5;This makes each value explicit and readable.
Constant Initialization
A const object normally needs to be initialized when it is created.
Correct:
const int value = 100;A declaration such as:
const int value;is generally ill-formed because a const object must be initialized.
constexpr Constants
C++ also provides constexpr for values that are required to be constant expressions.
Example:
constexpr int daysInWeek = 7;Another example:
constexpr double pi = 3.141592653589793;constexpr communicates that the value is intended to be usable in constant expressions.
For example:
constexpr int width = 10;
constexpr int height = 20;
constexpr int area = width * height;The compiler can evaluate area at compile time.
const vs constexpr
Although both can represent values that do not change, they have different purposes.
const | constexpr |
|---|---|
| Object cannot be modified through the const object | Declares a constant expression when applicable |
| Can represent a value determined at runtime | Must be initialized with a constant expression for an object |
| Useful for read-only objects | Useful when compile-time evaluation is required |
| More general | More restrictive and compile-time oriented |
Example:
int getValue();
const int a = getValue();a is const, but its value is obtained at runtime.
By contrast:
constexpr int b = 100;is a compile-time constant expression.
Integer Literals in C++
Integer literals represent whole-number values.
Examples:
10
42
1000
-25An important detail is that the minus sign in:
-25is not part of the integer literal itself. It is the unary minus operator applied to the literal 25.
Decimal Integer Literals
The most common integer literals use decimal notation:
int a = 10;
int b = 250;
int c = 100000;Decimal integer literals normally have type int, long, or long long depending on their value and suffix.
Binary Integer Literals
C++ supports binary integer literals using the 0b or 0B prefix.
Example:
int value = 0b1010;The binary value:
1010represents decimal:
10Binary literals are especially useful when working with:
Bit masks
Flags
Hardware
Binary protocols
Bitwise operations
Example:
unsigned int permissions = 0b1011;Octal Integer Literals
An integer beginning with 0 can represent an octal literal.
Example:
int value = 075;This is octal notation.
The decimal equivalent is:
61Be careful with leading zeroes because:
int number = 010;does not mean decimal 10.
It represents octal 10, which equals decimal 8.
For this reason, modern code should use octal notation deliberately rather than accidentally.
Hexadecimal Integer Literals
Hexadecimal literals begin with:
0xor:
0XExample:
int value = 0xFF;0xFF represents decimal:
255Hexadecimal literals are common in:
Memory addresses
Bit masks
Color values
Hardware programming
Low-level programming
Debugging
Example:
unsigned int mask = 0xFF;Integer Literal Separators
C++ allows apostrophes as digit separators.
For example:
int population = 1'000'000;
long long distance = 9'000'000'000LL;The apostrophes do not change the value.
They simply make large numbers easier to read.
Without separators:
long long value = 9000000000LL;With separators:
long long value = 9'000'000'000LL;The second version is often easier to read.
Integer Literal Suffixes
Literal suffixes can specify or influence the type of an integer literal.
Common suffixes include:
U
L
LL
UL
ULLExamples:
100U
100L
100LL
100UL
100ULLThese represent unsigned, long, long long, and combinations of those types.
Example:
unsigned long long value = 18'000'000'000ULL;Floating-Point Literals
Floating-point literals represent numbers containing a fractional component.
Examples:
3.14
10.5
0.25For example:
double price = 99.99;The literal 99.99 is a floating-point literal.
Floating-Point Literal Types
A floating-point literal without a suffix normally has type double.
Example:
double value = 3.14;You can use suffixes to specify other floating-point types.
f or F
Creates a float literal:
float value = 3.14f;l or L
Creates a long double literal:
long double value = 3.14L;Therefore:
3.14is normally a double literal,
while:
3.14fis a float literal.
Scientific Notation Literals
C++ supports scientific notation for floating-point literals.
Example:
double distance = 1.5e6;This means:
1.5 × 10⁶Another example:
double value = 2.5e-3;This means:
0.0025Scientific notation is useful for very large or very small values.
Character Literals
A character literal represents a single character and is written using single quotes.
Examples:
'A'
'B'
'7'
'?'Example:
char grade = 'A';A character literal such as:
'A'is different from the string literal:
"A"The first represents a character; the second represents a string.
Escape Character Literals
C++ provides escape sequences for special characters.
Common examples include:
| Escape | Meaning |
|---|---|
\n | New line |
\t | Horizontal tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\r | Carriage return |
\0 | Null character |
Example:
char newline = '\n';
char tab = '\t';You can also use them in strings:
std::cout << "Hello\nWorld";String Literals
String literals are sequences of characters written inside double quotes.
Example:
"Hello World"Another example:
const char* message = "Welcome to C++";A string literal has an array type consisting of const char elements, with a terminating null character.
For example:
"Cat"contains:
'C'
'a'
't'
'\0'Raw String Literals
C++ also supports raw string literals.
They are useful when you want backslashes and other characters to be treated mostly as ordinary characters.
Example:
const char* path = R"(C:\Users\John\Documents)";Without a raw string, backslashes may need escaping:
const char* path = "C:\\Users\\John\\Documents";Raw strings are particularly useful for:
File paths
Regular expressions
JSON
Multiline text
Embedded code
Boolean Literals
C++ has two Boolean literals:
true
falseExample:
bool isLoggedIn = true;
bool isAdmin = false;These are keywords representing Boolean values.
Null Pointer Literal
Modern C++ uses:
nullptras the null pointer literal.
Example:
int* ptr = nullptr;nullptr is preferred over the older practice of using 0 or NULL for null pointers.
It has type std::nullptr_t and can convert to pointer types.
User-Defined Literals
C++ allows programmers to define their own literal suffixes.
This feature is called user-defined literals.
For example, a program can define a literal such as:
12_kmand give it a custom meaning.
A simplified example:
#include <iostream>
constexpr long double operator""_km(long double value) {
return value * 1000.0L;
}
int main() {
auto distance = 5.0_km;
std::cout << distance << " meters\n";
}The custom suffix _km allows the programmer to express a domain-specific value directly in code.
User-defined literals are useful in specialized applications such as:
Units
Physical quantities
Embedded systems
Domain-specific libraries
Time and measurement APIs
Constant Expressions
A constant expression is an expression that can be evaluated at compile time under C++'s constant-expression rules.
For example:
constexpr int width = 10;
constexpr int height = 20;
constexpr int area = width * height;Here, the compiler can evaluate:
width * heightduring compilation.
This is useful for compile-time computations and APIs that require constant expressions.
Constants in Arrays
A constant expression can be useful when defining array bounds in contexts where a compile-time constant is required.
For example:
constexpr int size = 5;
int numbers[size];The value of size is available as a constant expression.
Modern C++ also provides containers such as std::array:
#include <array>
constexpr std::size_t size = 5;
std::array<int, size> numbers{};Named Constants vs Magic Numbers
A magic number is an unexplained numeric value placed directly in code.
For example:
double total = price * 1.18;What does 1.18 mean?
It could represent a tax rate, conversion factor, or something else.
A clearer version is:
constexpr double taxMultiplier = 1.18;
double total = price * taxMultiplier;Now the meaning is immediately visible.
Constants make code easier to maintain.
Example: Building a Calculator With Constants
#include <iostream>
int main() {
constexpr double taxRate = 0.18;
double price;
std::cout << "Enter price: ";
std::cin >> price;
double tax = price * taxRate;
double total = price + tax;
std::cout << "Tax: " << tax << '\n';
std::cout << "Total: " << total << '\n';
return 0;
}The tax rate is defined once and reused.
Example: Different Literal Forms
The following program demonstrates several C++ literal forms:
#include <iostream>
int main() {
int decimal = 100;
int binary = 0b1100100;
int octal = 0144;
int hexadecimal = 0x64;
double decimalValue = 3.14;
float floatValue = 3.14f;
long double longDoubleValue = 3.14L;
char letter = 'A';
bool active = true;
const char* message = "Hello C++";
int* pointer = nullptr;
std::cout << decimal << '\n';
std::cout << binary << '\n';
std::cout << octal << '\n';
std::cout << hexadecimal << '\n';
std::cout << decimalValue << '\n';
std::cout << floatValue << '\n';
std::cout << longDoubleValue << '\n';
std::cout << letter << '\n';
std::cout << active << '\n';
std::cout << message << '\n';
std::cout << pointer << '\n';
return 0;
}The first four integer values represent the same decimal number:
100but use different literal bases.
Common C++ Literal Types
| Literal example | Category |
|---|---|
100 | Integer literal |
0b1010 | Binary integer literal |
075 | Octal integer literal |
0xFF | Hexadecimal integer literal |
3.14 | Floating-point literal |
3.14f | float literal |
3.14L | long double literal |
'A' | Character literal |
"Hello" | String literal |
true | Boolean literal |
false | Boolean literal |
nullptr | Null pointer literal |
5_km | User-defined literal |
Constants and Literals: A Practical Comparison
Consider:
constexpr double pi = 3.141592653589793;There are two important concepts here:
pi
↓
named constant
3.141592653589793
↓
floating-point literalNow consider:
int radius = 10;Here:
radius
↓
variable
10
↓
integer literalAnd:
const char* name = "Tanmoy";Here:
name
↓
pointer object
"Tanmoy"
↓
string literalCommon Mistakes With C++ Constants and Literals
1. Confusing a Constant With a Literal
This:
const int maxValue = 100;does not mean maxValue is a literal.
maxValue is a named constant object.
100 is the literal.
2. Using the Wrong Quotes
Character:
char grade = 'A';String:
const char* grade = "A";Single quotes are used for character literals, while double quotes are used for string literals.
3. Forgetting Floating-Point Suffixes
Consider:
float value = 3.14;The literal 3.14 is a double literal that is then converted to float.
When you intentionally want a float literal, write:
float value = 3.14f;4. Accidentally Using Octal Notation
This:
int value = 010;is octal, not decimal 10.
It represents decimal 8.
Use:
int value = 10;for decimal 10.
5. Using NULL Instead of nullptr
Older C++ code may use:
int* ptr = NULL;Modern C++ should generally use:
int* ptr = nullptr;because nullptr has a dedicated null pointer type and avoids some overload-resolution problems associated with integer-based null representations.
6. Repeating Magic Numbers
Instead of:
double total = price * 0.18;
double tax = amount * 0.18;prefer:
constexpr double taxRate = 0.18;
double total = price * taxRate;
double tax = amount * taxRate;const vs #define
Before modern C++, programmers often used preprocessor macros for constants:
#define MAX_USERS 100Modern C++ generally prefers:
constexpr int maxUsers = 100;Why?
A typed constant:
constexpr int maxUsers = 100;has a type and follows normal C++ language rules.
A #define is a preprocessor substitution and does not create a typed C++ object.
For most ordinary constants, prefer const or constexpr over #define.
const vs constexpr vs #define
| Feature | const | constexpr | #define |
|---|---|---|---|
| Type checked | Yes | Yes | No |
| C++ object | Yes | Yes | No |
| Compile-time constant expression | Not always | Yes when applicable | Text substitution |
| Scope rules | Normal C++ scope | Normal C++ scope | Preprocessor scope |
| Recommended for constants | Yes | Yes, when compile-time evaluation is desired | Usually no |
Best Practices for C++ Constants and Literals
Use meaningful names
Prefer:
constexpr double taxRate = 0.18;over:
constexpr double x = 0.18;Prefer constexpr for compile-time constants
For example:
constexpr int maxConnections = 100;Use const for read-only objects that may be initialized at runtime
const int value = getValue();Use nullptr for null pointers
int* ptr = nullptr;Use literal suffixes deliberately
3.14f
100ULLUse digit separators for large numbers
long long population = 1'400'000'000LL;Avoid unexplained magic numbers
Replace them with appropriately named constants.
Use hexadecimal and binary notation when it improves readability
For example:
unsigned int mask = 0xFF;is often clearer than:
unsigned int mask = 255;when the value represents a byte mask.
Frequently Asked Questions
What is a literal in C++?
A literal is a value written directly in C++ source code, such as 100, 3.14, 'A', "Hello", true, or nullptr.
What is a constant in C++?
A constant is a value that cannot be modified through its constant declaration. It can be created using const or, when appropriate, constexpr.
What is the difference between a constant and a literal?
A constant is generally a named object or entity whose value cannot be modified. A literal is a value written directly in source code.
For example:
const int maxUsers = 100;maxUsers is a constant and 100 is an integer literal.
What are the different types of literals in C++?
Common C++ literal categories include:
Integer literals
Floating-point literals
Character literals
String literals
Boolean literals
Null pointer literal
User-defined literals
What is a binary literal in C++?
A binary integer literal uses the 0b or 0B prefix.
int value = 0b1010;The value is decimal 10.
What is a hexadecimal literal in C++?
A hexadecimal integer literal begins with 0x or 0X.
int value = 0xFF;This represents decimal 255.
What is a floating-point literal?
A floating-point literal represents a value with a fractional part or an exponent.
Examples:
3.14
2.5e3
3.14f
3.14LWhat is the difference between 3.14 and 3.14f?
3.14 is normally a double literal.
3.14f is a float literal.
What is constexpr in C++?
constexpr indicates that a variable or function is usable in constant expressions when its initialization or evaluation satisfies the relevant compile-time rules.
Example:
constexpr int size = 10;What is nullptr?
nullptr is C++'s null pointer literal. It is preferred over NULL or 0 when representing a null pointer.
What are user-defined literals?
User-defined literals allow programmers to create custom literal suffixes.
For example:
5_kmcan be given a custom meaning by defining the appropriate literal operator.
Suggested Graphic Design
Create a clean educational infographic titled:
“C++ Constants and Literals Explained”
Use a central split:
C++ CONSTANTS & LITERALS
│
┌────────────┴────────────┐
│ │
CONSTANTS LITERALS
│ │
const / constexpr ┌───────┼────────┐
│ │ │ │
const int x = 10; Integer Float Character
100 3.14 'A'
│
┌─────┴─────┐
│ │
String Boolean
"Hello" true/false
│
nullptr / UDLAdd a second section showing literal notation:
10 → Decimal
0b1010 → Binary
012 → Octal
0xFF → Hexadecimal
3.14 → Double
3.14f → Float
'A' → Character
"Hello" → String
true → Boolean
nullptr → Null pointerRunnable Code Example: C++ Constants and Literals
C++20 / C++23#include <iostream>
#include <string>
constexpr double PI = 3.141592653589793;
constexpr int BUFFER_SIZE = 1'024; // C++14 digit separator
int main() {
const int maxConnections = 500;
int binaryFlags = 0b10100101;
int hexColor = 0xFF5733;
std::string rawJson = R"({"status": "active", "code": 200})";
std::cout << "PI Constant: " << PI << "
";
std::cout << "Buffer Size: " << BUFFER_SIZE << " bytes
";
std::cout << "Binary Literal (0b10100101): " << binaryFlags << "
";
std::cout << "Raw JSON string: " << rawJson << "
";
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: What is the key advantage of constexpr over const in C++?
Q: What are Raw String Literals in C++?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
constexpr over const whenever a value is known at compile time.2. Replace
#define constants with constexpr variables for type safety and debugger symbol visibility.3. Use digit separators (
1'000'000) to improve readability of large numeric literals.