Constants and Literals

Loading concept...

🏛️ 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!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.