Coming Soon
This lesson is currently being developed
Literals
Understand different types of literal values in C++.
What to Expect
Comprehensive explanations with practical examples
Interactive coding exercises to practice concepts
Knowledge quiz to test your understanding
Step-by-step guidance for beginners
Development Status
Content is being carefully crafted to provide the best learning experience
Preview
Early Preview Content
This content is still being developed and may change before publication.
5.2 — Literals
In this lesson, you'll learn about literals in C++, understand the different types of literal values, and discover how to use them effectively in your programs.
What are literals?
A literal is a fixed value that is directly embedded in your source code. Unlike variables, literals represent actual values that don't change and are known at compile time.
Think of literals as the "raw ingredients" of your program - they are the actual numbers, characters, and text that you write directly into your code.
Types of literals
C++ supports several types of literals:
- Integer literals - Whole numbers
- Floating-point literals - Decimal numbers
- Character literals - Single characters
- String literals - Text sequences
- Boolean literals - True/false values
Let's explore each type in detail.
Integer literals
Integer literals represent whole numbers and can be written in different formats:
Decimal integer literals (base 10)
#include <iostream>
int main()
{
// Decimal integer literals
int positive = 42;
int negative = -17;
int zero = 0;
int large = 1000000;
std::cout << "Positive: " << positive << std::endl;
std::cout << "Negative: " << negative << std::endl;
std::cout << "Zero: " << zero << std::endl;
std::cout << "Large: " << large << std::endl;
return 0;
}
Output:
Positive: 42
Negative: -17
Zero: 0
Large: 1000000
Integer literal suffixes
You can specify the type of an integer literal using suffixes:
#include <iostream>
int main()
{
// Integer literal suffixes
long longValue = 42L; // L or l for long
long long bigValue = 42LL; // LL or ll for long long
unsigned int unsignedValue = 42U; // U or u for unsigned
// You can combine suffixes
unsigned long ulValue = 42UL; // UL for unsigned long
std::cout << "Long value: " << longValue << std::endl;
std::cout << "Big value: " << bigValue << std::endl;
std::cout << "Unsigned value: " << unsignedValue << std::endl;
std::cout << "Unsigned long: " << ulValue << std::endl;
return 0;
}
Output:
Long value: 42
Big value: 42
Unsigned value: 42
Unsigned long: 42
Digit separators (C++14 and later)
For better readability, you can use single quotes as digit separators:
#include <iostream>
int main()
{
// Digit separators make large numbers more readable
int million = 1'000'000;
int billion = 1'000'000'000;
long long huge = 123'456'789'012'345LL;
std::cout << "Million: " << million << std::endl;
std::cout << "Billion: " << billion << std::endl;
std::cout << "Huge number: " << huge << std::endl;
return 0;
}
Output:
Million: 1000000
Billion: 1000000000
Huge number: 123456789012345
Floating-point literals
Floating-point literals represent decimal numbers:
Basic floating-point literals
#include <iostream>
int main()
{
// Floating-point literals
double pi = 3.14159;
double smallValue = 0.001;
double negativeValue = -2.5;
double wholeAsFloat = 42.0;
std::cout << "Pi: " << pi << std::endl;
std::cout << "Small value: " << smallValue << std::endl;
std::cout << "Negative: " << negativeValue << std::endl;
std::cout << "Whole as float: " << wholeAsFloat << std::endl;
return 0;
}
Output:
Pi: 3.14159
Small value: 0.001
Negative: -2.5
Whole as float: 42
Scientific notation
Floating-point literals can use scientific notation with 'e' or 'E':
#include <iostream>
int main()
{
// Scientific notation
double speedOfLight = 2.998e8; // 2.998 × 10^8
double electronMass = 9.109e-31; // 9.109 × 10^-31
double avogadro = 6.022E23; // 6.022 × 10^23
std::cout << "Speed of light: " << speedOfLight << " m/s" << std::endl;
std::cout << "Electron mass: " << electronMass << " kg" << std::endl;
std::cout << "Avogadro's number: " << avogadro << std::endl;
return 0;
}
Output:
Speed of light: 2.998e+08 m/s
Electron mass: 9.109e-31 kg
Avogadro's number: 6.022e+23
Floating-point literal suffixes
#include <iostream>
int main()
{
// Floating-point suffixes
float floatValue = 3.14f; // f or F for float
double doubleValue = 3.14; // No suffix needed for double
long double ldValue = 3.14L; // L or l for long double
std::cout << "Float: " << floatValue << std::endl;
std::cout << "Double: " << doubleValue << std::endl;
std::cout << "Long double: " << ldValue << std::endl;
return 0;
}
Output:
Float: 3.14
Double: 3.14
Long double: 3.14
Character literals
Character literals represent single characters enclosed in single quotes:
Basic character literals
#include <iostream>
int main()
{
// Character literals
char letter = 'A';
char digit = '5';
char symbol = '@';
char space = ' ';
std::cout << "Letter: " << letter << std::endl;
std::cout << "Digit: " << digit << std::endl;
std::cout << "Symbol: " << symbol << std::endl;
std::cout << "Space: '" << space << "'" << std::endl;
return 0;
}
Output:
Letter: A
Digit: 5
Symbol: @
Space: ' '
Escape sequences
Special characters can be represented using escape sequences:
#include <iostream>
int main()
{
// Escape sequence literals
char newline = '\n'; // Line break
char tab = '\t'; // Tab character
char backslash = '\\'; // Backslash
char singleQuote = '\''; // Single quote
char doubleQuote = '\"'; // Double quote
std::cout << "First line" << newline << "Second line" << std::endl;
std::cout << "Column1" << tab << "Column2" << std::endl;
std::cout << "Backslash: " << backslash << std::endl;
std::cout << "Single quote: " << singleQuote << std::endl;
std::cout << "Double quote: " << doubleQuote << std::endl;
return 0;
}
Output:
First line
Second line
Column1 Column2
Backslash: \
Single quote: '
Double quote: "
Common escape sequences table
Escape Sequence | Character | Description |
---|---|---|
\n |
Newline | Move to next line |
\t |
Tab | Horizontal tab |
\r |
Carriage return | Return to line start |
\\ |
Backslash | Literal backslash |
\' |
Single quote | Literal single quote |
\" |
Double quote | Literal double quote |
\0 |
Null character | String terminator |
String literals
String literals represent sequences of characters enclosed in double quotes:
Basic string literals
#include <iostream>
int main()
{
// String literals
const char* greeting = "Hello, World!";
const char* name = "Alice";
const char* empty = "";
const char* withSpaces = "This string has spaces";
std::cout << greeting << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Empty string: '" << empty << "'" << std::endl;
std::cout << withSpaces << std::endl;
return 0;
}
Output:
Hello, World!
Name: Alice
Empty string: ''
This string has spaces
String literals with escape sequences
#include <iostream>
int main()
{
// String literals with escape sequences
const char* message = "Line 1\nLine 2\nLine 3";
const char* tabbed = "Name:\tJohn\nAge:\t25";
const char* quoted = "She said, \"Hello there!\"";
const char* path = "C:\\Users\\Username\\Documents";
std::cout << "Multi-line message:" << std::endl;
std::cout << message << std::endl << std::endl;
std::cout << "Tabbed data:" << std::endl;
std::cout << tabbed << std::endl << std::endl;
std::cout << "Quoted text: " << quoted << std::endl;
std::cout << "File path: " << path << std::endl;
return 0;
}
Output:
Multi-line message:
Line 1
Line 2
Line 3
Tabbed data:
Name: John
Age: 25
Quoted text: She said, "Hello there!"
File path: C:\Users\Username\Documents
Raw string literals (C++11)
Raw string literals allow you to include special characters without escape sequences:
#include <iostream>
int main()
{
// Raw string literals - no escape sequences needed
const char* regularString = "C:\\Users\\Name\\file.txt";
const char* rawString = R"(C:\Users\Name\file.txt)";
const char* regex = R"(\d+\.\d+\.\d+\.\d+)"; // IP address regex
const char* multiline = R"(This is a
multi-line string
with "quotes" and \backslashes)";
std::cout << "Regular string: " << regularString << std::endl;
std::cout << "Raw string: " << rawString << std::endl;
std::cout << "Regex pattern: " << regex << std::endl;
std::cout << "Multi-line raw string:" << std::endl;
std::cout << multiline << std::endl;
return 0;
}
Output:
Regular string: C:\Users\Name\file.txt
Raw string: C:\Users\Name\file.txt
Regex pattern: \d+\.\d+\.\d+\.\d+
Multi-line raw string:
This is a
multi-line string
with "quotes" and \backslashes
Boolean literals
Boolean literals represent true/false values:
#include <iostream>
int main()
{
// Boolean literals
bool isReady = true;
bool isFinished = false;
bool testPassed = true;
std::cout << "Is ready: " << isReady << std::endl;
std::cout << "Is finished: " << isFinished << std::endl;
std::cout << "Test passed: " << testPassed << std::endl;
// Boolean values displayed as numbers by default
std::cout << std::boolalpha; // Display as true/false
std::cout << "Is ready: " << isReady << std::endl;
std::cout << "Is finished: " << isFinished << std::endl;
return 0;
}
Output:
Is ready: 1
Is finished: 0
Test passed: 1
Is ready: true
Is finished: false
Using literals effectively
Combining literals in expressions
#include <iostream>
int main()
{
// Using different types of literals together
const double price = 19.99; // Floating-point literal
const double taxRate = 0.08; // Floating-point literal
const int quantity = 3; // Integer literal
const char currency = '$'; // Character literal
double subtotal = price * quantity;
double tax = subtotal * taxRate;
double total = subtotal + tax;
std::cout << "Item price: " << currency << price << std::endl;
std::cout << "Quantity: " << quantity << std::endl;
std::cout << "Subtotal: " << currency << subtotal << std::endl;
std::cout << "Tax: " << currency << tax << std::endl;
std::cout << "Total: " << currency << total << std::endl;
return 0;
}
Output:
Item price: $19.99
Quantity: 3
Subtotal: $59.97
Tax: $4.7976
Total: $64.7676
Literals vs. variables
#include <iostream>
int main()
{
// Literals are compile-time constants
int literalValue = 42; // 42 is an integer literal
const double pi = 3.14159; // 3.14159 is a floating-point literal
char grade = 'A'; // 'A' is a character literal
bool success = true; // true is a boolean literal
// Variables can change (unless const)
int variableValue = 10;
variableValue = 20; // This is allowed
// Literals cannot be assigned to
// 42 = variableValue; // Error! Can't assign to a literal
std::cout << "Literal-initialized value: " << literalValue << std::endl;
std::cout << "Pi constant: " << pi << std::endl;
std::cout << "Grade: " << grade << std::endl;
std::cout << "Success: " << success << std::endl;
std::cout << "Variable value: " << variableValue << std::endl;
return 0;
}
Output:
Literal-initialized value: 42
Pi constant: 3.14159
Grade: A
Success: 1
Variable value: 20
Best practices for using literals
1. Use appropriate literal types
// Good practices
float radius = 5.5f; // Use f suffix for float literals
double precision = 5.5; // No suffix needed for double
long largeNumber = 1000000L; // Use L suffix for long literals
2. Use digit separators for readability
// More readable large numbers
int population = 7'800'000'000;
long long distance = 9'460'730'472'580'800LL; // Light-year in kilometers
3. Use raw strings for complex text
// Better than escaped strings
const char* filePath = R"(C:\Program Files\MyApp\config.txt)";
const char* sqlQuery = R"(SELECT * FROM users WHERE name = 'John')";
4. Choose meaningful literal values
// Clear intent with descriptive literals
const int daysInWeek = 7;
const double freezingPointCelsius = 0.0;
const char fieldSeparator = ',';
Common literal mistakes
❌ Type mismatches
float value = 3.14; // Should be 3.14f for float
int result = 2.5; // Truncates to 2, probably not intended
✅ Correct type usage
float value = 3.14f; // Correct float literal
double result = 2.5; // Use double for decimal values
❌ Confusing character vs. string literals
char letter = "A"; // Error: "A" is a string literal, not character
✅ Proper character literals
char letter = 'A'; // Correct: 'A' is a character literal
Summary
Literals are the fundamental building blocks of C++ programs:
- Integer literals: Whole numbers (42, -17, 1'000'000)
- Floating-point literals: Decimal numbers (3.14, 2.5e8, 1.5f)
- Character literals: Single characters ('A', '\n', '\t')
- String literals: Text sequences ("Hello", R"(C:\path)")
- Boolean literals: True/false values (true, false)
Key points to remember:
- Literals are compile-time constants embedded in your source code
- Use appropriate suffixes to specify literal types (f, L, LL, U)
- Escape sequences represent special characters in literals
- Raw strings avoid the need for escape sequences
- Digit separators improve readability of large numbers
Quiz
- What is the difference between a literal and a variable?
- What suffix would you use to specify a float literal?
- What is the character literal for a tab character?
- How do raw string literals differ from regular string literals?
- Which of these is a valid integer literal with digit separators?
a) 1,000,000 b) 1'000'000 c) 1_000_000 d) 1.000.000
Practice exercises
Try working with different types of literals:
- Create variables initialized with literals of each type (int, float, char, string, bool)
- Write a program that displays a formatted receipt using various literal types
- Create a program that uses escape sequences to draw a simple ASCII art picture
- Practice using raw string literals to represent file paths and regular expressions
Explore More Courses
Discover other available courses while this lesson is being prepared.
Browse CoursesLesson Discussion
Share your thoughts and questions