SyntaxPilot
Courses/C++/Lesson 2

C++ · Lesson 2 of 40 · 19 min

Variables and data types

queued

These are the notes for C++ episode 2. While fixing the bills at Ravi bhaiya's mobile recharge shop, you will invent variables yourself: why a program needs them, how to declare, assign and change one, why int silently drops decimals and how brace initialization { } turns that silent bug into a compile error, then double, char, string, bool (and boolalpha), auto, sizeof, integer overflow with long long, and const. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and the output shown is the real output: a plain block right after the code, or a // prints ... comment next to the line that prints it.

The problem: Ravi bhaiya's recharge bill

Ravi bhaiya runs a mobile recharge shop at the corner of the colony. His most popular plan costs ₹299, and his nephew wrote a small C++ program that prints bills:

#include <iostream>
#include <string>
using namespace std;

int main() {
    cout << "1 recharge = " << 299 * 1 << endl;
    cout << "3 recharges = " << 299 * 3 << endl;
    cout << "5 recharges = " << 299 * 5 << endl;
    return 0;
}
1 recharge = 299
3 recharges = 897
5 recharges = 1495

Then tariffs go up and the plan becomes ₹349. Someone has to change every 299 by hand. In a hurry we change the first and third lines and miss the middle one:

cout << "1 recharge = " << 349 * 1 << endl;    // prints 1 recharge = 349
cout << "3 recharges = " << 299 * 3 << endl;   // prints 3 recharges = 897
cout << "5 recharges = " << 349 * 5 << endl;   // prints 5 recharges = 1745

The bill for three recharges still says 897. It should be 1047, so Ravi bhaiya loses ₹150 on every such order. And g++ said nothing, because to the compiler this code is perfectly valid. Three lines today; what if the program had three hundred?

From here on, every snippet goes inside main() of the program above (the same #include <iostream>, #include <string> and using namespace std; lines, and return 0; at the end).

Why the bill broke

  • One fact (the price) was copied in many places: change one copy, forget another, and the output is wrong, with no error.
  • Reading 299 * 3, nobody can tell what 299 means. A price? A pincode? A roll number? (A bare number like this is called a magic number.)

The fix: write the price once, give it a name, and use the name everywhere.

The fix: a variable is a labelled dabba

Think of the dabbas in your mum's kitchen. Each has a label: sugar, tea, salt.

In the kitchen In C++
The label on the dabba, "Price", tells you what's inside price: the variable's name
What's inside: 349. Take it out any time = 349: the value
Empty it and refill it with 399: same dabba, new contents price = 399;: change it in one place
int price = 349;
cout << "1 recharge = " << price * 1 << endl;    // prints 1 recharge = 349
cout << "3 recharges = " << price * 3 << endl;   // prints 3 recharges = 1047
cout << "5 recharges = " << price * 5 << endl;   // prints 5 recharges = 1745

All three are correct. Now the real magic: to make the price ₹399, change only the first line to int price = 399;:

1 recharge = 399
3 recharges = 1197
5 recharges = 1995

The whole bill updates by itself. You just invented the variable: a named box in memory that holds a value.

Anatomy of a variable

int price = 349; has five parts:

Part In int price = 349; Meaning
Type int what kind of box (whole numbers)
Name price the label you use in code
= assignment operator put the value on the right into the box on the left
Value 349 what goes inside
; semicolon ends the statement
int price;              // declare: make the box
price = 349;            // assign: fill the box
cout << price << endl;  // prints 349
price = 399;            // change: no "int" the second time!
cout << price << endl;  // prints 399
  • Declare = make the box. Assign = put a value in. Doing both in one line (int price = 349;) = initialize.
  • You write the type only when you make the box. Writing int price = 399; again gives error: redeclaration of 'int price'.
  • In C++, = means "put into", not the maths "is equal to". (Comparing uses ==, covered in the next episode.)

The next problem: the missing half GB

The plan gives 1.5 GB of data per day, and the bill must show it. We use the same int box:

int dataPerDay = 1.5;
cout << "Data per day: " << dataPerDay << " GB" << endl;
cout << "In 28 days: " << dataPerDay * 28 << " GB" << endl;
Data per day: 1 GB
In 28 days: 28 GB

It should be 42 GB. Fourteen GB vanished, with no error and no warning (not even with -Wall -Wextra; only the extra flag -Wconversion would warn). The customer will ask: where is the rest of my data?

Why? int means integer, a whole number. An int box has no room for a decimal part, so C++ cuts off everything after the point. It does not round; it chops toward zero: int a = 1.9; gives 1, and int b = -1.9; gives -1. Turning a value into a smaller type and losing part of it is called a narrowing conversion, and here it happened silently.

Brace initialization { }: make the bug loud

Silent bugs are the most dangerous, because you never find out. The = sign is like a careless helper who quietly pockets the change. C++ also has a strict shopkeeper: curly braces. Give the value in { } instead of after =, and if it doesn't fully fit in the box, g++ refuses to build the program.

int dataPerDay{1.5};
cout << "Data per day: " << dataPerDay << " GB" << endl;
cout << "In 28 days: " << dataPerDay * 28 << " GB" << endl;

g++ says:

main.cpp:6:20: error: narrowing conversion of '1.5e+0' from 'double' to 'int' [-Wnarrowing]

(1.5e+0 is just 1.5 written in scientific notation: 1.5 × 10⁰.) In plain words: you are squeezing a decimal number into a smaller int box, and something would fall out. The silent bug is now a loud compile error, caught before the program ever ran, not by an angry customer. That's why modern C++ uses braces a lot. When the value fits, braces work like =, and empty braces give zero:

int days{28};
double data{1.5};
int zero{};
cout << days << " " << data << " " << zero << endl;   // prints 28 1.5 0

Data types: the right container for each thing

In real life In C++ Holds Example
Egg tray: whole eggs, never half an egg int whole numbers 349, -5
Measuring jug: 0.5 litre, 1.5 litre double decimal numbers 1.5
One-letter size tag: S, M, L char exactly one character 'P'
Name plate on a door string text of any length "Priya"

C didn't have a string box; C++ gives it to you.

double: decimals done right

The right box for the data is double. Change only the first line of the 1.5 GB program:

double dataPerDay = 1.5;
Data per day: 1.5 GB
In 28 days: 42 GB

The data is back. Notice that cout needs no %f (as C's printf does): cout recognises the type by itself. Also notice 42, not 42.0: by default cout doesn't print trailing zeros.

float also holds decimals, but it is only accurate to about 7 significant digits; double is good for about 15. That's why double is the default choice for decimals in C++.

char and string

string name = "Priya";
char plan = 'P';
cout << "Customer: " << name << endl;          // prints Customer: Priya
cout << "Plan: " << plan << endl;              // prints Plan: P
cout << "Letters: " << name.length() << endl;  // prints Letters: 5
  • char holds exactly one character, in single quotes: 'P'.
  • string holds any amount of text, in double quotes: "Priya". It needs #include <string>.
  • A string is a smart box: name.length() tells you how many characters it has. The dot means "ask this string"; length() is a member function of string.

The secret: a char is a small number

In memory a char is stored as a number, its ASCII code. Capital P is 80. Do arithmetic with it and you get a number, not a letter:

char plan = 'P';
cout << plan << endl;        // prints P
cout << plan + 1 << endl;    // prints 81
cout << (int)plan << endl;   // prints 80

plan + 1 becomes an int (80 + 1), so cout prints 81. (int)plan is a cast: it asks C++ to treat the value as an int.

bool: yes or no

A customer asks: "Bhaiya, is my plan active?" Only two answers: yes or no, like a light switch, on or off. C++ has a box for this, bool, which holds only true or false.

bool active = true;
bool expired = false;
cout << "Active: " << active << endl;     // prints Active: 1
cout << "Expired: " << expired << endl;   // prints Expired: 0

Surprise: inside, a bool is just a number, true is 1 and false is 0, and that's what cout prints. For words, put boolalpha into cout once:

cout << boolalpha << "Active: " << active << endl;   // prints Active: true
cout << "Expired: " << expired << endl;               // prints Expired: false

boolalpha is a manipulator: it changes a setting of cout, and the setting stays on for every cout after it, which is why the second line also says false. (noboolalpha switches it back.)

auto: let the compiler choose

Do you always have to write the type? C++11 added a shortcut: auto. The compiler looks at the value and picks the right box itself. This is called type deduction.

auto price = 349;
auto data = 1.5;
auto plan = 'P';
cout << price << " " << data << " " << plan << endl;   // prints 349 1.5 P

349 makes price an int, 1.5 makes data a double, and 'P' in single quotes makes plan a char. Two rules:

  • auto needs a value, or what would the compiler look at? auto x; gives error: declaration of 'auto x' has no initializer.
  • While you're learning, write the type yourself, so you always know which box you made.

How big is each box? sizeof

Boxes come in sizes, like a tiny spice dabba, a medium everyday dabba and a big drum for a year's wheat. Memory is measured in bytes (1 byte = 8 bits, where a bit is a single 0 or 1). The sizeof operator tells you how many bytes a type uses:

cout << "char:      " << sizeof(char) << " byte" << endl;
cout << "bool:      " << sizeof(bool) << " byte" << endl;
cout << "int:       " << sizeof(int) << " bytes" << endl;
cout << "double:    " << sizeof(double) << " bytes" << endl;
cout << "long long: " << sizeof(long long) << " bytes" << endl;
char:      1 byte
bool:      1 byte
int:       4 bytes
double:    8 bytes
long long: 8 bytes

These are the sizes on this machine (64-bit Linux, g++). The C++ standard only sets minimums (for example, int must be at least 16 bits and long long at least 64), so another system could differ. Not sure? Ask sizeof.

Type Size here Range / values Use it for
char 1 byte one character (-128 to 127 as a number) 'P'
bool 1 byte true / false yes/no flags
short 2 bytes -32,768 to 32,767 rarely used
int 4 bytes -2,147,483,648 to 2,147,483,647 (about ±2.1 billion) default whole number
long long 8 bytes about ±9.2 × 10¹⁸ big counts
float 4 bytes about 7 significant digits memory-tight decimals
double 8 bytes about 15 significant digits default decimal
string varies any text names, messages

When a number is too big: overflow and long long

Ravi bhaiya counts all the data he sold in a year, in MB, in an int. The counter reaches the largest value an int can hold, and then one more MB is sold:

int totalMB = 2147483647;
totalMB = totalMB + 1;
cout << "Total MB: " << totalMB << endl;   // prints Total MB: -2147483648

Suddenly the total is negative, and there is no error. The box was full, so the number wrapped round to the most negative value, like an old meter going from 99999 to 00000. This is integer overflow. C++ assumes the programmer knows what they are doing. (Strictly, overflow of a signed type like int is undefined behaviour in C++: the standard promises nothing. Wrapping is what happened on this machine; never rely on it.)

The fix is a bigger box. Write long long instead of int in the first line, long long totalMB = 2147483647;, and run again:

Total MB: 2147483648

Exactly right, and unlike C there is no %lld to remember for cout. Rule: if a number can get really big, use long long.

Constants with const

Some values must never change, like the 18% GST on a recharge. If a new helper accidentally writes GST = 0.28;, every customer is overcharged. The fix: lock the dabba with const.

const double GST = 0.18;
GST = 0.28;
cout << GST << endl;

g++ refuses: main.cpp:7:9: error: assignment of read-only variable 'GST'

The lock worked: the compiler itself stopped the change. A const must get its value when it is made (const double GST; alone gives error: uninitialized 'const GST' [-fpermissive]). Constants are usually named in capital letters, so you can spot them from far away.

Naming rules

  • Allowed: letters, digits and underscore _ (price, plan2, data_per_day).
  • Can't start with a digit: int 2cups = 2; gives error: expected unqualified-id before numeric constant.
  • No spaces, - or @: int total price = 10; gives error: expected initializer before 'price'.
  • Not a keyword (a word C++ reserves for itself, like int, return, auto, bool): int return = 5; gives error: expected unqualified-id before 'return'.
  • Case sensitive: price and Price are two different names.
  • Convention: camelCase for variables (dataPerDay, totalMB), each new word starting with a capital; capitals for constants (GST).

Common mistakes (and the real g++ messages)

The video shows the first one live: int price = 349; then cout << Price << endl;. g++ points to line 7, the exact spot, and even suggests the fix: main.cpp:7:13: error: 'Price' was not declared in this scope; did you mean 'price'? Make the P small and it prints 349.

Mistake Code What g++ says Fix
Different capital letter cout << Price; error: 'Price' was not declared in this scope; did you mean 'price'? cout << price;
String in single quotes string name = 'Priya'; warning: character constant too long for its type, then error: conversion from 'int' to non-scalar type 'std::string' {aka 'std::__cxx11::basic_string<char>'} requested string name = "Priya";
Decimal into an int with braces int data{1.5}; error: narrowing conversion of '1.5e+0' from 'double' to 'int' [-Wnarrowing] double data{1.5};
Decimal into an int with = int data = 1.5; nothing: silently becomes 1 use double, or braces to catch it
Using an empty box int total; cout << total; often nothing (it printed 0 here, by luck); with -Wall: warning: 'total' is used uninitialized [-Wuninitialized] int total = 0;
Changing a constant GST = 0.28; error: assignment of read-only variable 'GST' don't, or drop const
Writing the type twice int price = 399; (again) error: redeclaration of 'int price' price = 399;
auto without a value auto x; error: declaration of 'auto x' has no initializer auto x = 5;
Counter past 2,147,483,647 int totalMB = 2147483647; totalMB + 1 nothing: prints -2147483648 long long totalMB

The uninitialized variable is the most dangerous: the box could hold anything left in memory, and the result can change from run to run. Always give a variable a starting value.

Mini project: Ravi bhaiya's recharge bill

Everything together: a constant, a string, a char, an int, doubles and a bool.

#include <iostream>
#include <string>
using namespace std;

int main() {
    const double GST = 0.18;
    string name = "Priya";
    char plan = 'P';
    int days = 28;
    double price = 349;
    double dataPerDay = 1.5;
    bool autoRenew = true;
    cout << "Customer: " << name << " (Plan " << plan << ")" << endl;
    cout << "Data: " << dataPerDay * days << " GB in " << days << " days" << endl;
    cout << "Price: " << price << " + GST " << price * GST << endl;
    cout << "Total: " << price + price * GST << endl;
    cout << boolalpha << "Auto-renew: " << autoRenew << endl;
    return 0;
}
Customer: Priya (Plan P)
Data: 42 GB in 28 days
Price: 349 + GST 62.82
Total: 411.82
Auto-renew: true
  • No %d, no %f: every box tells cout its own type.
  • dataPerDay * days mixes a double and an int; the result is a double (42).
  • price is a double even though 349 is whole, because the GST maths produces paise. Pause and try your own plan.

Practice

  1. Homework from the video: change the bill to an 84-day plan at ₹859 with 2 GB/day.
  2. Store your name in a string and print its length. Then print sizeof(float) and sizeof(short).
  3. Predict the output: int x = 7.99; auto y = 7.99; char c = 'A'; cout << x << " " << y << " " << c + 2 << endl;
  4. Using brace initialization, store the number of SIM cards, a phone balance of ₹45.50, a network letter, whether the phone is 5G and the city, each in the best type, and print them on one line with true/false as words.
  5. Make each of today's errors on purpose and read the message.
Solution

1. Keep the five cout lines of the mini project and change only the values (plan letter Q and auto-renew off are our choice):

const double GST = 0.18;
string name = "Priya";
char plan = 'Q';
int days = 84;
double price = 859;
double dataPerDay = 2;
bool autoRenew = false;
Customer: Priya (Plan Q)
Data: 168 GB in 84 days
Price: 859 + GST 154.62
Total: 1013.62
Auto-renew: false

2. The space counts as a character. Output is shown in the comments:

string myName = "Aarav Sharma";
cout << "Name: " << myName << endl;                  // Name: Aarav Sharma
cout << "Length: " << myName.length() << endl;       // Length: 12
cout << "float: " << sizeof(float) << " bytes" << endl;   // float: 4 bytes
cout << "short: " << sizeof(short) << " bytes" << endl;   // short: 2 bytes

3. It prints 7 7.99 67. x is an int, so 7.99 is chopped to 7; auto makes y a double; 'A' is 65, so c + 2 is the number 67.

4. It prints 2 45.5 J true Indore (cout drops the trailing zero; formatting money to two decimals comes later).

int simCards{2};
double balance{45.50};
char network{'J'};
bool is5G{true};
string city{"Indore"};
cout << boolalpha;
cout << simCards << " " << balance << " " << network << " " << is5G << " " << city << endl;

5. Compare your messages with the common-mistakes table above.

Quick quiz

What happens with this code?

int data{2.5};
cout << data << endl;
  • A. 2
  • B. 2.5
  • C. 3
  • D. Compile error
Answer

D: compile error. Braces don't allow narrowing: a double like 2.5 can't fit in an int, so g++ stops with main.cpp:6:14: error: narrowing conversion of '2.5e+0' from 'double' to 'int' [-Wnarrowing]. With int data = 2.5; it would compile and silently print 2 (verified).

Interview questions

  • Declaration vs assignment vs initialization? Declaration creates the variable (int price;), assignment puts a value into an existing one (price = 349;), initialization gives the value at creation (int price = 349; or int price{349};).
  • What is brace (list) initialization and why prefer it? int x{5}; forbids narrowing, so int x{1.5}; is a compile error instead of silent data loss. int x{}; gives zero.
  • What happens when you store 1.9 in an int? The decimal part is truncated toward zero: 1 (and -1.9 becomes -1). No rounding, and with = no error by default.
  • What does auto do? When can't you use it? The compiler deduces the type from the initializer at compile time (auto d = 1.5; is a double); the variable is still statically typed. auto x; with no initializer is an error.
  • Is the size of int fixed in C++? No. The standard guarantees minimums (int at least 16 bits, long long at least 64) and short ≤ int ≤ long ≤ long long. On typical 64-bit systems int is 4 bytes; check with sizeof.
  • What is integer overflow and how do you avoid it? A result outside the type's range, like 2147483647 + 1 in an int. For signed types it is undefined behaviour and usually wraps negative. Use a bigger type such as long long.
  • char vs string? char is one character in single quotes, stored as a small number (ASCII code). std::string is a class from <string> holding any text in double quotes, and it knows its length (.length()).
  • Why does cout print 1 for true? A bool is stored as 1 or 0 and printed as a number by default; cout << boolalpha prints the words.
  • What does const do, and why must a const be initialized? It makes the variable read-only, so any later assignment is a compile error; since it can never be assigned later, it must get its value at creation.

Glossary

Term Plain meaning Example
Variable A named box in memory that holds a value you can change int price = 349;
Value What is stored inside the box 349
Data type The kind of box; decides what it can hold and its size int, double
Declare Create a variable (make the box) int price;
Assign Put a value into an existing variable price = 399;
Initialize Create a variable and give it a value in one step int price = 349;
Operator A symbol or word that does something to values *, <<, sizeof
Assignment operator = "Put the right side into the left box", not "is equal to" days = 28;
Statement One complete instruction, ending in ; price = 399;
Magic number A bare number in code whose meaning is unclear 299 * 3
int Integer: a whole number with no decimal part, about ±2.1 billion int days = 28;
double Decimal number, about 15 accurate digits double data = 1.5;
float Smaller decimal type, about 7 significant (accurate) digits float f = 2.5;
char One character in single quotes char plan = 'P';
string Text of any length in double quotes (needs <string>) string name = "Priya";
bool True/false value bool active = true;
long long 8-byte whole number for huge values long long totalMB = 2147483648;
short 2-byte whole number (smaller range than int) short s = 100;
Truncation Cutting off the decimal part without rounding int a = 1.9; gives 1
Narrowing conversion Converting to a smaller type that can't hold the whole value double 1.5 into int
Initializer The starting value given when a variable is created the 349 in int price = 349;
Brace initialization Giving the initializer in { } (also called list initialization); forbids narrowing int days{28};
Scientific notation A number written as digits × a power of 10; g++ shows 1.5 as 1.5e+0 2.5e+0 = 2.5
Compile error g++ refuses to build the program and shows a message assignment of read-only variable 'GST'
Warning g++ builds the program but points out something suspicious character constant too long for its type
Silent bug Wrong result with no error or warning int dataPerDay = 1.5;
cout The output stream (a flow of characters) that prints to the screen cout << price;
#include Brings a library's tools into your file #include <string>
std:: / namespace The standard library's family name; using namespace std; lets you drop it std::string = string
boolalpha Makes cout print true/false instead of 1/0 cout << boolalpha;
Manipulator Something put into cout that changes how it prints boolalpha, endl
auto Lets the compiler pick the type from the value auto data = 1.5;
Type deduction The compiler working out a type by itself auto x = 5; is int
sizeof Operator that gives a type's size in bytes sizeof(int) is 4 here
Byte / bit A bit is one 0 or 1; a byte is 8 bits int = 4 bytes = 32 bits
ASCII code The number stored for a character 'P' is 80
Cast Asking C++ to treat a value as another type (int)plan
Class / object A class is a blueprint for a smart type; an object is one box made from it string is a class, name an object
Member function A function that belongs to an object, called with a dot name.length()
Statically typed Every variable's type is fixed at compile time (even with auto) auto x = 5; stays int
Signed A type that can hold negative numbers int holds -5
Overflow A result too big for its box, which wraps or misbehaves 2147483647 + 1 gives -2147483648
Undefined behaviour Code whose result the C++ standard doesn't promise signed int overflow
const Makes a variable read-only: it can never be changed after it is created const double GST = 0.18;
Keyword A word reserved by C++; can't be a variable name int, return, auto
Case sensitive Capital and small letters count as different price ≠ Price
camelCase Joining words with each new word capitalised totalMB
Scope The part of the code where a name is known "not declared in this scope"
g++ flags Options for the compiler: -O2 optimise, -std=c++17 use C++17, -Wall / -Wconversion extra warnings g++ -O2 -std=c++17 main.cpp -o main

Summary

  • A variable is a labelled box: type name = value;. Change the value in one place and the whole program follows.
  • Declare (make), assign (fill), initialize (both). Write the type only once. = means "put into".
  • int holds whole numbers and silently chops decimals: 1.5 becomes 1. Use double for decimals.
  • Brace initialization int x{1.5}; turns that silent bug into a narrowing conversion error.
  • char = one character in single quotes; string = text in double quotes (#include <string>, .length()). A char is secretly a number ('P' = 80).
  • bool prints 1/0; cout << boolalpha prints true/false. auto picks the type for you, but needs a value.
  • sizeof gives sizes in bytes (here: char 1, bool 1, int 4, double 8, long long 8). Past 2,147,483,647 an int overflows; use long long.
  • const locks a value; constants are named in capitals. Always initialize your variables.

Next episode: operators in C++. Four friends split a ₹250 bill and C++ says each pays ₹62. Where did the rest go? Plus what % does, ++, and && / ||.