Skip to main content

Constants, Literals and Modifiers

Constants and Literals in C++

Why Bother About Something So "Small"?

"Wait… literals? Constants? That sounds… tiny. Are they really worth our attention?"

Absolutely. If a program is like a recipe, then literals are the actual ingredients: 2 cups of sugar, 3 eggs, a pinch of salt. Without them, you’re just stirring air.

We’re going to explore these tiny pieces of C++ in such a way that they become powerful tools in your programming belt — not just things you memorize, but things you understand.

1. Integer Literals — Just Numbers? Not Quite.

What is an integer literal, exactly?

Imagine you’re writing a birthday card and you write “You are 10 today!” That “10” is fixed. You didn’t ask a computer for it — you wrote it straight in. That’s what an integer literal is: a raw, whole number you write directly into your code.

int age = 10;

Here, 10 is a literal. It’s not a variable. It’s not a formula. It’s the actual value.

Now here’s where it gets fun — and maybe a little tricky. C++ doesn’t just understand "normal" numbers. It speaks multiple number languages.

Why would one number have four ways of being written?

Let’s take the number 10.

  • Decimal (what we’re used to): 10
  • Octal (base 8): 012
  • Hexadecimal (base 16): 0xA
  • Binary (base 2): 0b1010

"Wait, why the weird formats?"

Imagine you’re an electrician. You think in wires and binary (0s and 1s). Or a computer hardware engineer — hex is your daily bread. Different formats are used in different domains. C++ is just being multilingual.

Let’s break it down:

  • Decimal (Base 10): What we count with every day.
  • Octal (Base 8): Used in older Unix systems and file permissions.
  • Hexadecimal (Base 16): Used in colors (#FF0000 is red), memory addresses, error codes.
  • Binary (Base 2): Computers’ native language.

Let’s try it in code:

int decimal = 10; // Normal
int octal = 012; // 10 in octal = 1*8 + 2 = 10
int hex = 0xA; // A in hex = 10
int binary = 0b1010; // 1*8 + 0*4 + 1*2 + 0 = 10

“But I just want to write numbers!”
Yes — and you can. But now you know why sometimes 075 might not be what you think. In octal, 075 = 61.

What’s up with those letter suffixes like U or L?

Let’s play detective:

unsigned int a = 4000000000; // Oops! Error!

Why the error? The number is too big for a regular int.

We can fix it with a suffix:

unsigned int a = 4000000000U; // Now it's fine

Here’s a mini guide:

  • U or u: Unsigned
  • L or l: Long
  • LL or ll: Long Long
  • Combine them: 123UL, 456ll

It’s like telling C++: “Hey, treat this number carefully — it’s special.”

Common Beginner Pitfalls:

  • 075 is not seventy-five! It’s octal!
  • Writing a number too large for its type (causes overflow!)
  • Forgetting that int has a size limit (typically 2^31−1)

2. Floating-point Literals — Real Numbers, Real Precision

“Wait… why do some numbers have dots, and some don’t?”

Great question! Let’s imagine something together.

You're pouring water into a glass. Your glass says “1 cup”, but you’re not always perfect with your pouring, right? Maybe today you poured a little more, maybe 1.5 cups. Or maybe you poured just a little, like 0.25 cups.

Now, in the real world, we deal with in-between values like that all the time. But computers? By default, they like things clean and whole: 1, 2, 3… no mess. So to help computers understand these in-between, real-life values, C++ gives us a tool: floating-point numbers.

“Why are they called ‘floating-point’ numbers?”

Okay, this one’s a bit fun.

Imagine a little decimal point floating along the number — it can move! It’s not fixed. Sometimes the point floats to the left, sometimes to the right, depending on how big or small the number is.

So:

  • The point “floats” = we can have really small numbers (like 0.00001)
  • Or really big numbers (like 123456789.0)
  • All in one type of number: a floating-point number

Let’s write a few:

float price = 2.99;
double gravity = 9.81;
long double pi = 3.141592653589793L;

These are all floating-point literals — real numbers written directly into code.

“What are they made of?”

Every floating-point number is made of 3 or 4 parts:

  1. The integer part → before the dot (3.14 → the 3)
  2. The decimal point → the dot itself
  3. The fractional part → after the dot (3.14 → the 14)
  4. (Sometimes) the exponent part → if you want to show huge or tiny numbers

Like this:

double atoms = 6.02e23;

This means 6.02 × 10²³ — a number so big we usually only see it in science.

The e means “exponent.” It says: “Take this number and multiply it by 10 this many times.”

“But why does the computer care so much about the dot?”

Because dots bring complexity. Computers aren’t great at understanding infinite tiny values, so floating-point numbers have limits. They approximate values. That means they don’t always get them perfectly right.

It’s like drawing a circle using square pixels — close, but not perfect.

“What are the different kinds of floating-point numbers?”

In C++, we have three types of floating-point numbers. Think of them like different cup sizes:

  1. float – Small cup (uses less memory, less precision)
  2. double – Medium cup (used most often)
  3. long double –  Giant fancy cup (used for scientific precision)

“How do I tell the computer which cup to use?”

By using suffixes. These are just little letters you put after your number to say, “Hey computer, use this size!”

  • f or F → This is a float
  • l or L → This is a long double
  • No letter? → C++ assumes it’s a double

Let’s try this:

float discount = 0.15f;           // small cup
double temp = 36.6;               // default cup
long double constant = 2.718L;    // giant cup

“Why not just always use double? Isn’t it safer?”

That’s a smart question! double is definitely safe and precise enough for most everyday things.

But sometimes:

  • You’re writing a game for a small phone. Memory matters.
  • You’re running a calculation a million times. Speed matters.
  • You’re doing physics simulations where every decimal matters.

So, choosing the right type means you’re choosing a balance between:

  • Accuracy
  • Memory
  • Speed

Common Confusions (and how to avoid them):

“Can I write 2,5 in C++?”

Nope! That’s a trap for many beginners, especially if you're used to languages where commas mean decimals (like in parts of Europe).

In C++, you must use a dot:

double correct = 2.5;   // OK
double wrong = 2,5;     // Compiler will be confused!

“Are float and double the same?”

Not at all! They’re like twin siblings with different talents:

  • float can store ~7 digits of precision
  • double can store ~15 digits of precision

So:

float f = 123456789.123456789f;
double d = 123456789.123456789;

Try printing both. The float will chop off details. The double will remember more.

A Real-World Analogy: The Ruler Game

Let’s say we’re measuring a table.

  • With a ruler that has only whole inches → you’ll get something like “72 inches”
  • With a ruler that has half-inch marks → you can say “72.5 inches”
  • With a digital laser → you can get “72.468239 inches”

That's exactly what float, double, and long double are doing!

Quick Summary:

Concept

Meaning

float

Small, fast, but not super precise

double

Bigger, more precise, best default

long double

Super precise, but rarely needed unless in science/math-heavy code

., not ,

Always use a dot for decimals in C++

e notation

For really big or really small numbers

Use suffixes

f, L to tell C++ what type you're using

Curious Challenge:

Try this code:

#include <iostream>
using namespace std;

int main() {
    float f = 1.0 / 3.0;
    double d = 1.0 / 3.0;
    long double ld = 1.0 / 3.0;
 
    cout << "float:       " << f << endl;
    cout << "double:      " << d << endl;
    cout << "long double: " << ld << endl;
 
    return 0;
}

See how different each result looks? It’s like zooming in on a photo — the closer you look, the more details appear.

Final Thought on Floating-Point Literals

They might look simple — just numbers with dots, right? But they open the door to a whole world of accuracy, performance tuning, and real-world modeling.

Understanding them well now means you’ll avoid weird bugs, unpredictable calculations, and get way more control over how your code behaves.


3. Boolean Literals — Only Two Options? Or a Whole World of Decisions?

“What even is a Boolean?”

Okay! Imagine we’re playing with a big red button.

You press it once: ON.
You press it again: OFF.

That's it.

Only two choices. No maybes. No “kind of.” Just YES or NO. TRUE or FALSE.

This little idea — this tiny “two-choice” thing — is called a Boolean.

💡
The name “Boolean” comes from a math genius named George Boole. He said: “Hey, what if we did math with true and false instead of just numbers?” Boom — that idea changed everything.

“Wait… only two options? Just true or false?”

Yes. That’s all. And yet... those two words can build entire programs, guide robot arms, decide video game wins, and control real-world machines.

Let’s look at them in C++:

bool isLightOn = true;
bool isDoorOpen = false;

Here, bool means “Boolean type.” And we’re telling the computer: “Hey, store whether this thing is true or false.”

“So, true and false are just words?”

Well... yes and no.

To us, they’re nice, friendly English words.
But to the computer, everything is numbers.

So under the hood:

  • true = 1
  • false = 0

That’s right. Your big fancy “truth” is really just a 1 in disguise

Let’s peek under the hood:

bool isRaining = true;
cout << isRaining << endl; // Will print: 1

So if you ever print a Boolean, don’t be surprised when you see 1 or 0. That’s how computers speak.

“Can I just use 1 and 0 instead of true and false?”

You can... but should you?

Let’s try both:

bool isHappy = 1;     // okay
bool isSad = 0;       // also okay

C++ will accept it. But it’s like calling your best friend by their last name. Technically fine, but... kinda cold.

Always prefer:

bool isHappy = true;
bool isSad = false;

Way more expressive. It's like reading a story instead of decoding Morse code.

Here’s something super interesting:

bool test = 5;

Wait… what? That’s not even true or false. It’s five.

But here’s the magic:

  • Any non-zero number is treated as true
  • Only 0 is false

So:

bool a = 5;      // true
bool b = -17;    // true
bool c = 0;      // false

The Boolean doesn’t care what number it is, just whether it’s zero or not.

“So… are all numbers just kinda pretending to be true or false?”

Exactly! In Boolean land, we call this truthiness.

We’re not checking if a number is “good” or “bad” — just “is there something there?” If yes, we say it’s true.

Kind of like:

  • A cup with some juice → true
  • An empty cup → false

Mistake #: Mixing up assignment and comparison

This one’s classic, and it bites millions of beginners:

if (flag = false) {
    // Uh-oh! This is an assignment, not a check
}

That single = means “set this to false.” So flag becomes false, and the condition becomes false too.

What you meant was:

if (flag == false) {
    // This is a comparison
}

Rule of thumb: When checking, use two equals signs.

Real-Life Analogy Time!

Think of a video game. Your character has different states:

  • Is he alive? → true/false
  • Has he picked up the sword? → true/false
  • Is he invisible? → true/false

All these are Boolean flags — like little checkboxes.

bool hasKey = true;
bool isInDungeon = false;

This helps the game decide what to do next:

if (hasKey && !isInDungeon) {
    openCastleDoor();
}

It’s like building a conversation with the computer: “Only open the door if I have the key and I’m not in the dungeon!”

“Can Booleans do math?”
Kinda. But it's logic math, not normal math.

Here are the basic tools:

Operation

Meaning

Example

!

NOT

!true = false

&&

AND

true && false = false

This lets us write smart decisions:

if (isLoggedIn && hasPermission) {
    showDashboard();
}

Or:

if (!isAlive) {
    gameOver();
}

Boolean Values in Real Programs

Booleans are like tiny gatekeepers. They decide:

  • Should we run this code or skip it?
  • Should we show a message or stay quiet?
  • Is this data valid or not?

They’re tiny, but they run the show.

Think Like This:
If you can ask a yes or no question in real life — it probably maps to a Boolean in code.

  • Did the user click “OK”? → true
  • Is the number negative? → true
  • Is it raining? → true
  • Is pizza better than salad? → (okay, that's a debate but still)

Common Beginner Mistakes (and how to fix them):

Mistake

Why it's bad

Better Way

Using 1 and 0

Technically works, but unclear

Use true, false

Comparing with == 1

Works, but risky with edge cases

Just use if (flag)

Using = instead of ==

You’re changing the value!

Always double-check comparisons

Forgetting bool is a type

C++ won't assume — you have to tell it

bool isCool = true;

Try This Challenge!

#include <iostream>
using namespace std;
 
int main() {
    bool hasApples = true;
    bool hasOranges = false;
 
    if (hasApples || hasOranges) {
        cout << "We have fruit!" << endl;
    }
 
    if (!hasOranges) {
        cout << "No oranges today." << endl;
    }
 
    return 0;
}

What do you think this prints? Can you guess?

Final Thoughts

Booleans are like teddy bear decisions:

  • Do I feel sleepy?
  • Is the light on?
  • Is it bedtime yet?

They help us say “yes” or “no” in the clearest way possible.

So whenever you’re deciding in your code — think Boolean. Think true/false. And let your program choose wisely.


4. Character Literals — Letters That Mean More Than They Show

“What is a character literal? Is it like a letter?”

Yes! But it’s not just letters. It can be numbers. It can be symbols. It can even be invisible things like spaces and newlines.

In C++, we call them character literals, and they look like this:

char grade = 'A';
char symbol = '?';
char digit = '7';
char newline = '\n';

"char" means: “Hey computer, store just one character.”
So 'A' is a character. So is '?', so is '\n', and even a space like ' ' is a character.
But wait — why are they in single quotes?

 “Why single quotes? Can I use double quotes?”

Good catch, junior coder! That’s a very important question.

Here’s the rule:

  • 'A' → character literal → uses single quotes
  • "A" → string literal → uses double quotes

But what’s the difference between a character and a string?

Let’s break it down with a snack analogy:

'A' is like a single apple
"A" is like a box that holds apples (even if there's just one inside)

In code terms:

char letter = 'A';         // Good
char word = "A";           //  Error! That’s a string, not a character

So if you ever see double quotes, you’re looking at a string — not just a character.

“What if I write '9' and 9? They look the same!”

Ooooh, that’s a classic brain-bender. But they’re totally different.

Let’s look at this:

char digitChar = '9';  // This is the character '9'
int number = 9;        // This is the number 9

So:

  • '9' is a symbol. The character nine.
  • 9 is an integer. The number nine.

And guess what? '9' doesn’t actually store the number 9 inside. It stores something called its ASCII value, which is 57.

ASCII is like a secret code where every character has a number.

So:

char c = '9';
cout << (int)c << endl; // This will print: 57

“What’s ASCII? Is it like a magic character number chart?”

ASCII (pronounced "ask-ee") is a table where:

  • 'A' = 65
  • 'B' = 66
  • 'a' = 97
  • '0' = 48
  • '9' = 57
  • ' ' (space) = 32

It's how computers translate letters into numbers so they can store and understand them.

So every 'A' you write isn’t just a letter — it’s actually 65 wearing a costume.

“What if I try to put two letters in one character?”

Nope. Can’t do that. Character means one character only.

char bad = 'ab'; // Error: Too many characters!

C++ will panic. It’ll say: “Hey, buddy, I only have room for one. Not a crowd.”
If you need two characters, you probably want a string, like this:

string good = "ab";

“What if I want characters that don’t show anything?”

Great question! Characters aren’t just the visible stuff. There are invisible characters too — like:

  • '\n' → newline (moves to the next line)
  • '\t' → tab (adds a space gap)
  • ' ' → space
  • '\\' → backslash
  • '\'' → single quote
  • '\"' → double quote

These are called escape sequences — like secret codes.

Example:

char newline = '\n';
cout << "Line one\nLine two";

That will print:
Line one
Line two

Just because we used the magical newline character \n.

“Can characters be more than just English? What about emojis or hearts?”

Now you're thinking globally!

In old C++, characters were only 1 byte — that’s tiny. Enough for English, numbers, and symbols, but not for things like:

  • ❤️
  • 🌍
  • こんにちは

But since C++11, we got Unicode support, which means:

Syntax

Meaning

Example

u'x'

UTF-16 character

char16_t heart = u'';

U'x'

UTF-32 character

char32_t smile = U'😀';

L'x'

Wide character

wchar_t yen = L'¥';

char16_t heart = u'♥';   // Yes, now even hearts can live in your code!

Common Mistakes:

Mistake

Why it's bad

How to fix

'ab'

Only one character allowed

Use a string: "ab"

"a" assigned to char

String is not a character

Use 'a'

Confusing '9' with 9

Character vs integer

Be clear what you need

Forgetting escape characters

'\n' is not just text — it does something

Learn escape sequences


5. String Literals — Words, Sentences, and Secret Endings

“What even is a string literal?”
Okay, imagine you’re writing a note to your friend:
"Hi, want to play tag after school?"
That whole sentence, in quotes, is a string. And in C++, when we type:

std::cout << "Hello, world!";

That "Hello, world!" is a string literal — a bunch of characters wrapped inside double quotes.

Let’s repeat that loud and proud:

If it’s in double quotes, it’s a string!

“But wait — isn’t a string just like a character?”

Nice try! But remember: a character is one tiny letter or symbol — like 'A', 'z', or '7'.

A string is a whole lineup of characters standing together — like "Hello" or "1234" or "!".

Let’s compare:

char letter = 'H';           // Just the letter H
const char* message = "Hi";  // A full string — H and i together!

One is a solo singer
The other is a choir

“What’s really hiding inside a string?”
Great question, detective! Let’s peek behind the curtain.

When you write: "Hi"

The computer actually stores it like this:

Character

H

i

\0

Index

0

1

2

Wait... what’s that \0 at the end?

That’s called the null terminator. It’s like a period at the end of a sentence, but for computers.

It tells the computer: “Hey! That’s the end of the string. Don’t read beyond this!”

Without \0, C++ would keep reading whatever garbage is in memory after the string — and your code could crash or misbehave.

So remember: "Hi" actually means: 'H', 'i', '\0'

“Can strings have special characters inside them?”

Yes! And they’re super helpful.

C++ strings can include escape sequences — those little \ codes that do cool things.

Here are a few string superpowers:

Code

What It Does

Example Output

\n

New line

"Hello\nWorld" → HelloWorld

\t

Tab (indent)

"Name:\tAlice" → Name: Alice

\"

Prints a double quote

"She said, \"Hi!\""

\\

Prints a backslash

"C:\\Files" → C:\Files

So this:

std::cout << "One\nTwo\nThree";

Prints:
One
Two
Three

Cool, right?

“So is a string just a bunch of characters stuck together?”

YES! It’s like a necklace of beads, and each bead is a character:

"cat" → 'c', 'a', 't', '\0'

C++ stores strings as arrays of characters, ending with the magical null terminator \0.

In technical terms:

const char* greeting = "Hello!";

This is an array of type char, stored in memory with a pointer.

“What about different kinds of strings? Like with hearts or emojis?”

Boom — excellent question. Before C++11, strings were kinda boring. Only basic English-like characters.

But now, we have Unicode!

So we can write strings that include:

  • Emojis
  • Asian scripts こんにちは
  • Special symbols ©™

C++11 gave us special string literal prefixes:

Prefix

Encoding

Example

u8

UTF-8

u8"hi"

u

UTF-16

u"hi"

U

UTF-32

U"hi"

L

Wide char

L"hi"

So now we can do this:

auto emoji = u8"😀";

auto japanese = u"こんにちは";

auto wide = L"Wide world!";

The world isn’t just "ABC" anymore — now it’s "🌍🚀🎶" too.

Common Mistakes That Catch Beginners

Let’s shine a flashlight on the dark corners where bugs like to hide.

Mistake

Why it’s a problem

How to fix it

'hello'

That’s NOT a string! It’s invalid char

Use "hello" instead

Forgetting \0

If you're making strings manually, it can break things

Always end with '\0'

Using single quotes for multiple characters

Only use single quotes for ONE character

Use double quotes for strings

Trying to change "Hello" directly

String literals are read-only

Copy to a char[] to modify

Example:

char wrong = 'hello'; // Too many characters
const char* correct = "hello"; // Good

 Special Tip: Multi-line Strings!

You can break strings across lines using the backslash \:

cout << "This is \
one long line!";

And since C++11, we have raw string literals, so you can include line breaks inside strings:

cout << R"(Line 1
Line 2
Line 3)";

That prints:
Line 1
Line 2
Line 3

Raw strings start with R"( and end with )", and they ignore escape sequences inside.

Let’s Play: What’s This String Doing?

  1. "Hi\nThere" → ?
  2. "He said, \"Hi\"" → ?
  3. "\\server\\path" → ?

Answers:

  1. Prints:

Hi
There

  1. He said, "Hi"
  2. \server\path

A string literal is more than text in quotes. It’s a container of meaning. It can be:

  • A name: "Alice"
  • A message: "Game Over"
  • A sentence: "Welcome to C++!"
  • Or even a whole poem

And deep inside, it's just:

  • A sequence of characters
  • Stored with love and care
  • Ending with a tiny invisible \0 that says “The end.”

So when you write:

"Let's learn C++ from LearnYard"

You're not just typing letters. You're writing magic spells that the computer can read out loud.


6. Constants — Because Some Things Shouldn’t Change (Ever!)

“Why would we need something that can’t change?”

Let’s pretend for a moment that we’re baking cookies.
We need 1 cup of sugar. Once we start mixing, should we be allowed to randomly say:
“Hmm, now let’s make it 5 cups instead!”

No way! That would ruin the recipe.

Same thing in code. Sometimes, you have values that are so important, so sacred, that once you set them, they should never, ever, ever change.

That’s where constants come in.

“So what exactly is a constant?”

A constant is a value that’s set once and locked forever. Like a sticky note that says:

"Do not touch. This value is final."

Let’s say we want to store the number Pi (you know, the one from circles?):

const double PI = 3.14159;

Now, PI is a constant. If we try to change it later?

PI = 4.5; // ERROR! Not allowed!

C++ will throw a tantrum and say:

“Nope! You said this value wouldn’t change. Stick to your word!”

“But why do we need to ‘lock’ values?”

Good question, little coder! Let’s think like detectives.

Imagine we’re solving a mystery. We find this clue in our code:

area = PI * radius * radius;

If we know that PI is a constant, we can be sure it’s always 3.14159.
Nobody can sneak in and change it to 2.718.

This gives us:

  • Safety (no accidental changes)
  • Clarity (we know it's fixed)
  • Optimization (C++ can work faster when it knows something won’t change)

“Okay… so how do we create constants?”

There are 3 ways to make constants in C++.
Let’s walk through them one by one — like choosing from a toolbox.

1. #define — The Old, Shouty Way

#define PI 3.14

This is like using scissors and tape to stick a label on something.

The compiler sees PI and replaces it with 3.14 before it even compiles your code.

But there’s a problem…

  • No type safety
  • No scoping (it’s global)
  • It’s kind of “invisible” to the C++ type system

That means you could accidentally do something like:

#define MAX "ten"
int x = MAX; // What??

The compiler gets confused. "ten" is a string, but we’re trying to store it in an int!

2. const — The Friendly, Modern Way

const int maxScore = 100;

Here’s why const is awesome:

Type-safe, follows scope rules, easy to understand, you can even use it with arrays and pointers.

If you write:

const float pi = 3.14;

Then later do:

pi = 5.0; // Nope! Const says “hands off!”

The compiler says:

“You promised not to touch pi. And I’m holding you to it.”

3. constexpr — The Superpower!

Now here’s where things get fun.

constexpr int items = 10;

This means:

“I don’t just want this value to stay the same — I want it to be known at compile time.”

Wait, wait… What’s compile time?

Imagine a robot packing lunchboxes. If it knows beforehand that each box needs 10 cookies, it can prep super fast.

But if it only finds out at lunchtime, it’ll be slower.

So:

  • const means “this won’t change later”
  • constexpr means “this is constant and known early”

It’s faster. Smarter. And perfect for things like array sizes or templates.

“So when should I use each one?”

Tool

Use it when...

#define

You’re writing old-style or low-level code

const

You want a safe, typed value that won’t change

constexpr

You want a constant known at compile time

Most of the time? Just use const or constexpr. They’re best friends with modern C++.

Common Pitfalls — Let’s not trip!

Let’s catch some beginner stumbles before they happen:

Mistake

Why it’s bad

What to do instead

Trying to change a const

C++ will scream!

Don’t assign a new value

Forgetting const where needed

Your variable might accidentally get modified

Use const to freeze what’s fixed

Mixing up const and constexpr

Not all constants are compile-time constants

Use constexpr when needed early

Using #define for everything

Harder to debug, no type checks

Prefer const or constexpr

Playtime! Guess What Happens:

const int score = 10;
score = 20;

Compiler error! You said “score” is constant.

#define COUNT 5
int apples[COUNT];

This works… but it’s old-school. Not type-safe.

constexpr int size = 4;
int table[size];

This is the most modern, efficient way!

Conclusion

Literals and constants may seem small, but they are the foundation of every C++ program. From numbers and characters to true/false values and unchangeable constants, they give our code meaning and structure. Mastering these basics is like learning to speak the language of C++ — one word at a time.