đď¸ C++ Constants and Literals: The Unchanging Treasures
Imagine you have a treasure chest with special locked boxes inside. Once you put something in a locked box and close it, nobody can change whatâs insideâEVER. Thatâs what constants are in C++!
đŻ What Are We Learning?
Think of your program as a recipe book:
- Variables are like ingredients you can swap out
- Constants are like the chefâs secret recipeâcarved in stone, never changing!
đŚ Part 1: Constants and the const Keyword
The Magic Lock đ
When you write const, youâre putting a magical lock on a value. Once locked, it stays the same forever!
Simple Example:
const int MY_AGE = 10;
// MY_AGE will ALWAYS be 10
// You can NEVER change it!
Why Use Constants?
Think about the speed of lightâit never changes! Or Ď (pi) = 3.14159⌠Scientists donât want anyone accidentally changing these values.
Real Life Examples:
const double PI = 3.14159;
const int DAYS_IN_WEEK = 7;
const int HOURS_IN_DAY = 24;
The Rules of Constants
graph TD A[Create a Constant] --> B[Give it a value] B --> C[Lock it forever!] C --> D[Use it anywhere] D --> E[But NEVER change it]
What happens if you try to change a constant?
const int MAGIC_NUMBER = 42;
MAGIC_NUMBER = 100; // â ERROR!
// The compiler says "NO WAY!"
Two Ways to Create Constants
Way 1: const keyword (The Modern Way) â
const int MAX_SCORE = 100;
Way 2: #define (The Old Way)
#define MAX_SCORE 100
Tip: Use constâitâs safer and smarter!
đ˘ Part 2: Numeric Literals
Whatâs a Literal?
A literal is the actual value you write in your code. When you type the number 5, thatâs a literalâit literally means five!
Integer Literals (Whole Numbers)
You can write numbers in different âlanguagesâ:
| Style | Example | What it Means |
|---|---|---|
| Decimal | 42 |
Regular counting (base 10) |
| Octal | 052 |
Starts with 0 (base 8) |
| Hexadecimal | 0x2A |
Starts with 0x (base 16) |
| Binary | 0b101010 |
Starts with 0b (base 2) |
Fun Example:
int decimal = 42; // Regular
int octal = 052; // Same as 42!
int hex = 0x2A; // Same as 42!
int binary = 0b101010; // Same as 42!
All four variables hold the SAME value: 42!
Floating-Point Literals (Decimal Numbers)
These are numbers with decimal points, like money!
double price = 19.99; // Regular
double big = 1.5e6; // 1,500,000
double tiny = 3.14e-2; // 0.0314
The e means âtimes 10 to the power ofâ:
1.5e6= 1.5 Ă 10âś = 1,500,000
Adding Suffixes (Labels)
You can add letters to tell C++ the exact type:
long big_num = 1000000L; // L = long
unsigned positive = 42U; // U = unsigned
float price = 9.99F; // F = float
long long huge = 123LL; // LL = long long
đ Part 3: String and Character Literals
Character Literals (Single Letters)
A character is ONE letter, number, or symbol in single quotes:
char grade = 'A';
char digit = '5';
char symbol = '@';
Escape Sequences (Secret Codes!)
Some characters are invisible or special. We use backslash \ to write them:
| Code | What It Does |
|---|---|
\n |
New line (like pressing Enter) |
\t |
Tab space |
\\ |
A real backslash |
\' |
Single quote |
\" |
Double quote |
Example:
char newline = '\n';
char tab = '\t';
cout << "Hello\nWorld";
// Prints:
// Hello
// World
String Literals (Words & Sentences)
A string is text in double quotes:
string greeting = "Hello, World!";
string name = "Alice";
Raw Strings (No Escape Needed!)
Sometimes you want to write exactly what you see:
// Normal string (escapes needed)
string path = "C:\\Users\\Name";
// Raw string (write naturally!)
string path = R"(C:\Users\Name)";
Raw strings start with R"( and end with )"
String Prefixes (Different Flavors)
// Regular string
"Hello"
// Wide string (for international chars)
L"Hello"
// UTF-8 string
u8"Hello"
// UTF-16 string
u"Hello"
// UTF-32 string
U"Hello"
đ¨ Part 4: User-Defined Literals
Create Your Own Magic!
Imagine if you could write 5_km and C++ knows you mean 5 kilometers! Thatâs what user-defined literals do.
Example: Distance Converter
// Define your own literal
long double operator""_km(
long double km) {
return km * 1000; // to meters
}
// Now use it!
auto distance = 5.0_km;
// distance = 5000 (meters)
Built-in User Literals (Since C++14)
C++ has some ready-made ones:
#include <chrono>
#include <string>
using namespace std::literals;
// Time literals
auto sec = 5s; // 5 seconds
auto ms = 100ms; // 100 milliseconds
// String literal
auto str = "Hello"s; // std::string
How It Works
graph TD A[You write 5_km] --> B[C++ sees the _km] B --> C[Calls your function] C --> D[Returns 5000] D --> E[Magic complete!]
More Examples:
// Define weight in pounds to kg
constexpr double operator""_lb(
long double lb) {
return lb * 0.453592;
}
auto weight = 150.0_lb;
// weight â 68.04 kg
đŽ Quick Recap
graph TD A[Constants & Literals] --> B[const keyword] A --> C[Numeric Literals] A --> D[String/Char Literals] A --> E[User-Defined Literals] B --> B1[Never changes!] C --> C1[int, float, hex...] D --> D1[Text and characters] E --> E1[Custom suffixes]
đĄ Remember This!
| Concept | Think Of It As⌠|
|---|---|
const |
A locked treasure box |
| Numeric Literal | Numbers you type directly |
| Character | One letter in âsingle quotesâ |
| String | Words in âdouble quotesâ |
| User-Defined | Your own custom magic suffix |
đ You Did It!
Now you know:
- â
How to create unchanging values with
const - â Different ways to write numbers (decimal, hex, binary)
- â How to work with text and special characters
- â How to create your own custom literals!
Constants are like promises in your codeâonce made, never broken!