🧱 Section 1 · Foundations 🟢 Beginner MODULE 02

Variables, Data Types & Operators

⏱️ 25 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Section 140%
🎯 What you'll learn: How to declare and initialize variables, C++'s core primitive types and their real sizes, type inference with auto, the arithmetic/comparison/logical operator families, assignment shorthand, increment/decrement, and the classic integer-vs-floating-point division gotcha that trips up almost every beginner.

Declaring & Initializing Variables

A variable is a named piece of memory that holds a value. In C++, every variable must be declared with a type — this is different from Python, where a variable's type is only decided when a value is assigned to it. In C++, the type is fixed at the point of declaration and the compiler enforces it.

variables.cpp — Declaring Different Types
C++
// variables.cpp
// Declaring and printing variables of different types

#include <iostream>
#include <string>

int main() {
    int age = 25;
    double price = 19.99;
    float temperature = 36.6f;
    char grade = 'A';
    bool isStudent = true;
    std::string name = "Maria";

    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Price: " << price << std::endl;
    std::cout << "Temperature: " << temperature << std::endl;
    std::cout << "Grade: " << grade << std::endl;
    std::cout << "Is student: " << isStudent << std::endl;

    return 0;
}
📝
Declaration vs. initialization
int age; declares a variable without giving it a value — it holds garbage memory until assigned. int age = 25; declares and initializes it in one step. Always initialize your variables; reading an uninitialized variable is undefined behavior in C++.
⚠️
bool prints as 0 or 1, not true/false
By default, std::cout prints bool values as 1 (true) or 0 (false), not the words "true"/"false". You'll see this in the output of the example above for isStudent.

C++'s Primitive Data Types

C++ gives you fine-grained control over exactly what kind of data a variable stores — and how much memory it uses. The sizes below are the typical values on most modern 32/64-bit desktop platforms; the C++ standard technically leaves exact sizes implementation-defined, so they can vary on unusual hardware or embedded compilers.

🔢
int — 4 bytes (typical)
Whole numbers, roughly ±2.1 billion on most platforms. Size is implementation-defined, not guaranteed by the standard.
🎯
double — 8 bytes (typical)
Double-precision floating point. The default choice for decimal numbers — about 15–17 significant digits of precision.
📉
float — 4 bytes (typical)
Single-precision floating point. Less precise than double, uses half the memory. Literals need an f suffix, like 36.6f.
🔤
char — 1 byte
A single character, written in single quotes like 'A'. Internally stored as a small integer code.
bool — true or false
Holds only true or false. Typically occupies 1 byte in memory even though it only needs 1 bit of information.
📜
std::string — text
Not a built-in primitive — it's a Standard Library class from <string> that manages a growable sequence of characters for you.
Why does the exact size matter?
Choosing the right type isn't just style — it directly affects memory usage and performance. A char array of a million elements uses roughly a quarter of the memory an equivalent int array would. In performance-sensitive or embedded code, these choices genuinely matter.

Type Inference with auto

Writing out long type names repeatedly can get tedious. The auto keyword tells the compiler: "figure out the type yourself, from whatever I initialize this variable with." The type is still fixed at compile time — auto is not dynamic typing, it's just a shortcut for the compiler to do the typing for you.

auto_demo.cpp — Letting the Compiler Infer Types
C++
// auto_demo.cpp
#include <iostream>
#include <string>

int main() {
    auto x = 10;                       // deduced as int
    auto y = 3.14;                     // deduced as double
    auto name = std::string("Alex"); // deduced as std::string

    std::cout << x << " " << y << " " << name << std::endl;
    return 0;
}
⚠️
auto still needs an initializer
auto x; with no value on the right is a compile error — there's nothing for the compiler to infer the type from. auto only works when you initialize the variable on the same line you declare it.

Arithmetic Operators

C++ supports the standard arithmetic operators: + (add), - (subtract), * (multiply), / (divide), and % (modulo — the remainder after division).

arithmetic.cpp — Operators & the Division Gotcha
C++
// arithmetic.cpp
#include <iostream>

int main() {
    int a = 7;
    int b = 2;

    std::cout << "a + b = " << (a + b) << std::endl;
    std::cout << "a - b = " << (a - b) << std::endl;
    std::cout << "a * b = " << (a * b) << std::endl;
    std::cout << "a / b = " << (a / b) << std::endl; // integer division -> 3
    std::cout << "a % b = " << (a % b) << std::endl; // remainder -> 1

    double da = 7.0;
    double db = 2.0;
    std::cout << "da / db = " << (da / db) << std::endl; // 3.5

    return 0;
}
🐛
The classic gotcha: integer division truncates
When both operands of / are integers, C++ performs integer division — the result is truncated toward zero, so 7 / 2 gives 3, not 3.5. To get a decimal result, at least one operand must be a floating-point type (double or float). This catches almost every C++ beginner at least once.

Comparison & Logical Operators

Comparison operators (==, !=, <, >, <=, >=) compare two values and produce a bool. Logical operators combine or invert boolean values: && (AND — true only if both sides are true), || (OR — true if either side is true), and ! (NOT — flips true/false).

logic.cpp — Comparisons & Boolean Logic
C++
// logic.cpp
#include <iostream>

int main() {
    int age = 20;
    bool hasID = true;

    std::cout << (age >= 18) << std::endl;              // 1 (true)
    std::cout << (age >= 18 && hasID) << std::endl;    // 1 (true)
    std::cout << (age < 18 || !hasID) << std::endl;      // 0 (false)

    return 0;
}
💡
Don't confuse = with ==
A single = is the assignment operator — it stores a value. A double == is the equality comparison — it checks if two values are equal. Writing if (age = 18) instead of if (age == 18) is a classic bug: it silently assigns 18 to age instead of comparing.

Assignment Shorthand & Increment/Decrement

C++ offers compound assignment operators that combine an arithmetic operation with assignment: +=, -=, *=, /=, %=. It also has dedicated increment (++) and decrement (--) operators for adding or subtracting exactly 1.

shorthand.cpp — Compound & Increment Operators
C++
// shorthand.cpp
#include <iostream>

int main() {
    int score = 10;
    score += 5;   // same as: score = score + 5;   -> 15
    score -= 2;   // same as: score = score - 2;   -> 13
    score *= 2;   // same as: score = score * 2;   -> 26
    score /= 4;   // same as: score = score / 4;   -> 6 (integer division)
    std::cout << "score = " << score << std::endl;

    int counter = 0;
    counter++;   // counter is now 1
    ++counter;   // counter is now 2
    std::cout << "counter = " << counter << std::endl;

    return 0;
}
🔎
Pre-increment vs. post-increment
++counter (pre-increment) increments first, then evaluates to the new value. counter++ (post-increment) evaluates to the old value, then increments. When the result isn't used in the same expression — as in the example above — they behave identically. The difference only matters when you use the result immediately, like int x = counter++; vs int x = ++counter;.

Lesson Summary

Let's recap everything you learned in this lesson:

Every C++ variable has a fixed type, checked at compile time — unlike Python's dynamic typing.
Core primitives: int, double, float, char, bool — plus std::string from the Standard Library. Sizes shown are typical, not guaranteed by the standard.
auto lets the compiler infer a variable's type from its initializer — it's still statically typed, just less typing for you.
Integer division truncates7 / 2 is 3, not 3.5. Use a floating-point operand to get a decimal result.
Comparison operators return bool; &&, ||, and ! combine or invert them.
Compound assignment (+=, -=...) and increment/decrement (++, --) are shorthand for common update patterns.
🧩 Knowledge Check — Lesson 2
Answer all 5 questions to test your understanding. Instant feedback on every answer.
1. What is the typical size of an int on most modern desktop platforms?
2. What does auto x = 5; do?
3. What is the result of 7 / 2 when both operands are int?
4. Which operator checks logical AND in C++?
5. What does x += 3; do?
💪
Coding Challenge — Lesson 2
Apply what you learned · Beginner Level

Now it's your turn to write real code. Compile and run it with g++ or an online compiler.

Challenge: Rectangle Calculator 📐

Write a program called rectangle.cpp that declares the length and width of a rectangle as double variables (pick any values you like, e.g. 7.5 and 3.0), then computes and prints:

Length: 7.5
Width: 3
Area: 22.5
Perimeter: 21

Rules: Area = length × width. Perimeter = 2 × (length + width). Use double for all four values so division/multiplication stays precise. Print each value with its own std::cout line.
💡 Show hints if you're stuck
  • Declare: double length = 7.5; and double width = 3.0;
  • Compute area: double area = length * width;
  • Compute perimeter: double perimeter = 2 * (length + width);
  • Print with std::cout << "Area: " << area << std::endl;
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 2 Complete!

You now know how C++ stores and manipulates data. Next up: teaching your programs to make decisions with control flow.

Module 02 of 26 Section 1 — C++ Foundations