Topic 10 of 91 2. C++ Fundamentals Interactive Tutorial

C++ Constants and Literals: Fixed Values and Literal Forms

13 mins read Last updated: 26 Sep 2026 18,100 views

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:

After this declaration, you cannot change the value:

Constants 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:

main.cpp
Run Online
100
3.14
'A'
"Hello"
true
nullptr

These are all literals.

For example:

In this statement:

  • age is a variable.

  • 35 is an integer literal.

Another example:

main.cpp
Run Online
const double pi = 3.141592653589793;

Here:

  • pi is a constant object.

  • 3.141592653589793 is a floating-point literal.


Constants vs Literals

Constants and literals are related, but they are not the same thing.

FeatureConstantLiteral
MeaningA value that cannot be modified through that constant objectA value written directly in source code
Has a name?Usually yesUsually no
Exampleconst int max = 100;100
Can be reused by name?YesYou can repeat the literal, but it has no variable name
Example typeConstant objectInteger, floating-point, character, string, Boolean, etc.

Consider:

maxScore is a named constant.

100 is a literal.


Why Use Constants?

Constants make programs easier to understand and maintain.

Instead of writing:

main.cpp
Run Online
double price = amount * 0.18;
double tax = subtotal * 0.18;

you can define:

main.cpp
Run Online
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:

main.cpp
Run Online
const int maxAttempts = 3;

std::cout << maxAttempts;

Trying to modify it:

produces a compilation error.


Declaring Multiple Constants

You can declare several constants separately:

main.cpp
Run Online
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:

A declaration such as:

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:

main.cpp
Run Online
constexpr int daysInWeek = 7;

Another example:

main.cpp
Run Online
constexpr double pi = 3.141592653589793;

constexpr communicates that the value is intended to be usable in constant expressions.

For example:

main.cpp
Run Online
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.

constconstexpr
Object cannot be modified through the const objectDeclares a constant expression when applicable
Can represent a value determined at runtimeMust be initialized with a constant expression for an object
Useful for read-only objectsUseful when compile-time evaluation is required
More generalMore restrictive and compile-time oriented

Example:

main.cpp
Run Online
int getValue();

const int a = getValue();

a is const, but its value is obtained at runtime.

By contrast:

is a compile-time constant expression.


Integer Literals in C++

Integer literals represent whole-number values.

Examples:

An important detail is that the minus sign in:

is 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:

main.cpp
Run Online
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:

The binary value:

represents decimal:

Binary literals are especially useful when working with:

  • Bit masks

  • Flags

  • Hardware

  • Binary protocols

  • Bitwise operations

Example:

main.cpp
Run Online
unsigned int permissions = 0b1011;

Octal Integer Literals

An integer beginning with 0 can represent an octal literal.

Example:

This is octal notation.

The decimal equivalent is:

Be careful with leading zeroes because:

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:

or:

Example:

0xFF represents decimal:

Hexadecimal literals are common in:

  • Memory addresses

  • Bit masks

  • Color values

  • Hardware programming

  • Low-level programming

  • Debugging

Example:


Integer Literal Separators

C++ allows apostrophes as digit separators.

For example:

main.cpp
Run Online
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:

main.cpp
Run Online
long long value = 9000000000LL;

With separators:

main.cpp
Run Online
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:

Examples:

main.cpp
Run Online
100U
100L
100LL
100UL
100ULL

These represent unsigned, long, long long, and combinations of those types.

Example:

main.cpp
Run Online
unsigned long long value = 18'000'000'000ULL;

Floating-Point Literals

Floating-point literals represent numbers containing a fractional component.

Examples:

For example:

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:

You can use suffixes to specify other floating-point types.

f or F

Creates a float literal:

l or L

Creates a long double literal:

main.cpp
Run Online
long double value = 3.14L;

Therefore:

is normally a double literal,

while:

is a float literal.


Scientific Notation Literals

C++ supports scientific notation for floating-point literals.

Example:

This means:

Another example:

This means:

Scientific 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:

Example:

A character literal such as:

is different from the string literal:

The first represents a character; the second represents a string.


Escape Character Literals

C++ provides escape sequences for special characters.

Common examples include:

EscapeMeaning
\nNew line
\tHorizontal tab
\\Backslash
\'Single quote
\"Double quote
\rCarriage return
\0Null character

Example:

main.cpp
Run Online
char newline = '\n';
char tab = '\t';

You can also use them in strings:

main.cpp
Run Online
std::cout << "Hello\nWorld";

String Literals

String literals are sequences of characters written inside double quotes.

Example:

Another example:

main.cpp
Run Online
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:

contains:


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:

main.cpp
Run Online
const char* path = R"(C:\Users\John\Documents)";

Without a raw string, backslashes may need escaping:

main.cpp
Run Online
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:

Example:

main.cpp
Run Online
bool isLoggedIn = true;
bool isAdmin = false;

These are keywords representing Boolean values.


Null Pointer Literal

Modern C++ uses:

as the null pointer literal.

Example:

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:

and give it a custom meaning.

A simplified example:

main.cpp
Run Online
#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:

main.cpp
Run Online
constexpr int width = 10;
constexpr int height = 20;
constexpr int area = width * height;

Here, the compiler can evaluate:

during 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:

main.cpp
Run Online
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:

main.cpp
Run Online
#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:

main.cpp
Run Online
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:

main.cpp
Run Online
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

main.cpp
Run Online
#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:

main.cpp
Run Online
#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:

but use different literal bases.


Common C++ Literal Types

Literal exampleCategory
100Integer literal
0b1010Binary integer literal
075Octal integer literal
0xFFHexadecimal integer literal
3.14Floating-point literal
3.14ffloat literal
3.14Llong double literal
'A'Character literal
"Hello"String literal
trueBoolean literal
falseBoolean literal
nullptrNull pointer literal
5_kmUser-defined literal

Constants and Literals: A Practical Comparison

Consider:

main.cpp
Run Online
constexpr double pi = 3.141592653589793;

There are two important concepts here:

main.cpp
Run Online
pi
↓
named constant

3.141592653589793
↓
floating-point literal

Now consider:

Here:

main.cpp
Run Online
radius
↓
variable

10
↓
integer literal

And:

main.cpp
Run Online
const char* name = "Tanmoy";

Here:

main.cpp
Run Online
name
↓
pointer object

"Tanmoy"
↓
string literal

Common Mistakes With C++ Constants and Literals

1. Confusing a Constant With a Literal

This:

does not mean maxValue is a literal.

maxValue is a named constant object.

100 is the literal.


2. Using the Wrong Quotes

Character:

String:

Single quotes are used for character literals, while double quotes are used for string literals.


3. Forgetting Floating-Point Suffixes

Consider:

The literal 3.14 is a double literal that is then converted to float.

When you intentionally want a float literal, write:


4. Accidentally Using Octal Notation

This:

is octal, not decimal 10.

It represents decimal 8.

Use:

for decimal 10.


5. Using NULL Instead of nullptr

Older C++ code may use:

Modern C++ should generally use:

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:

main.cpp
Run Online
double total = price * 0.18;
double tax = amount * 0.18;

prefer:

main.cpp
Run Online
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:

Modern C++ generally prefers:

main.cpp
Run Online
constexpr int maxUsers = 100;

Why?

A typed constant:

main.cpp
Run Online
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

Featureconstconstexpr#define
Type checkedYesYesNo
C++ objectYesYesNo
Compile-time constant expressionNot alwaysYes when applicableText substitution
Scope rulesNormal C++ scopeNormal C++ scopePreprocessor scope
Recommended for constantsYesYes, when compile-time evaluation is desiredUsually no

Best Practices for C++ Constants and Literals

Use meaningful names

Prefer:

main.cpp
Run Online
constexpr double taxRate = 0.18;

over:

main.cpp
Run Online
constexpr double x = 0.18;

Prefer constexpr for compile-time constants

For example:

main.cpp
Run Online
constexpr int maxConnections = 100;

Use const for read-only objects that may be initialized at runtime

main.cpp
Run Online
const int value = getValue();

Use nullptr for null pointers

Use literal suffixes deliberately

Use digit separators for large numbers

main.cpp
Run Online
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:

is often clearer than:

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:

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.

The value is decimal 10.

What is a hexadecimal literal in C++?

A hexadecimal integer literal begins with 0x or 0X.

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:

What 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:

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:

can 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:

Architecture Diagram
             C++ CONSTANTS & LITERALS
                       │
          ┌────────────┴────────────┐
          │                         │
      CONSTANTS                  LITERALS
          │                         │
   const / constexpr        ┌───────┼────────┐
          │                 │       │        │
   const int x = 10;      Integer  Float   Character
                         100       3.14     'A'
                                  │
                            ┌─────┴─────┐
                            │           │
                         String      Boolean
                         "Hello"     true/false
                            │
                       nullptr / UDL

Add a second section showing literal notation:

main.cpp
Run Online
10       → Decimal
0b1010   → Binary
012      → Octal
0xFF     → Hexadecimal
3.14     → Double
3.14f    → Float
'A'      → Character
"Hello"  → String
true     → Boolean
nullptr  → Null pointer

Runnable Code Example: C++ Constants and Literals

C++20 / C++23
main.cpp
Run Online
#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 Prep
Q

Q: What is the key advantage of constexpr over const in C++?

A: `const` guarantees that a variable cannot be modified after initialization, but its initialization value can be computed at runtime. `constexpr` guarantees that the variable is computed at compile-time, allowing it to be used in template parameters, array sizes, and static assertions.
Q

Q: What are Raw String Literals in C++?

A: Raw string literals (`R"(...)"`) treat backslashes and escape characters as literal text without escaping, making regular expressions and file paths much cleaner to write.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Prefer 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.