Lesson 2 • Beginner
Variables & Data Types
Learn to store, name, and manipulate different kinds of data in C++ — the foundation of every program you'll ever write.
What You'll Learn
- ✓ All fundamental C++ data types
- ✓ How to declare and initialize variables
- ✓ Constants and the const keyword
- ✓ Type casting and sizeof operator
What Are Variables?
A variable is a named container that stores a value in memory. Think of variables like labeled boxes — the label is the variable name, and the box holds your data.
Unlike Python or JavaScript, C++ is statically typed — you must declare the type of data a variable will hold before using it. This gives you more control and catches errors at compile time.
Declaration Syntax
type variableName = value; // Declare and initialize
type variableName; // Declare only (uninitialized)
int x = 5, y = 10, z = 15; // Multiple of same typeC++ Data Types at a Glance
| Type | Size | Range | Example |
|---|---|---|---|
int | 4 bytes | -2.1B to 2.1B | int age = 25; |
double | 8 bytes | 15 decimal digits | double pi = 3.14; |
float | 4 bytes | 7 decimal digits | float t = 36.6f; |
char | 1 byte | Single character | char g = 'A'; |
bool | 1 byte | true / false | bool ok = true; |
string | varies | Any text | string s = "Hi"; |
Basic Data Types
Declare and print all fundamental C++ data types
#include <iostream>
#include <string>
using namespace std;
int main() {
// Integer — whole numbers
int age = 25;
int score = -10;
// Double — decimal numbers
double price = 19.99;
double pi = 3.14159;
// Float — less precision than double
float temperature = 36.6f; // Note the 'f' suffix
// Character — single character
char grade = 'A';
char symbol = '#';
// Boolean — true or false
bool isStudent = true;
bool hasPassed
...Constants — Values That Never Change
Use the const keyword to create values that cannot be modified after initialization. Constants make your code safer and more readable.
const double TAX_RATE = 0.20; // Cannot be changed
const int MAX_LIVES = 3; // Game constant
const string VERSION = "1.0.0"; // App versionNaming convention: Use UPPER_SNAKE_CASE for constants to distinguish them from regular variables.
Constants & Calculations
Use const to define unchangeable values in a circle calculator
#include <iostream>
using namespace std;
int main() {
// Constants — values that cannot change
const double PI = 3.14159265;
const int MAX_PLAYERS = 100;
const string APP_NAME = "MyApp";
// PI = 3.14; // ERROR! Cannot modify a const
// Using constants in calculations
double radius = 5.0;
double area = PI * radius * radius;
double circumference = 2 * PI * radius;
cout << "=== Circle Calculator ===" << endl;
cout << "Radius: " << radius
...Type Casting & sizeof
Convert between types and check memory sizes
#include <iostream>
using namespace std;
int main() {
// Implicit casting (automatic)
int wholeNumber = 10;
double decimalNumber = wholeNumber; // int → double (safe)
cout << "Implicit: " << decimalNumber << endl; // 10.0
// Implicit narrowing (data loss!)
double pi = 3.14159;
int truncated = pi; // double → int (loses decimals)
cout << "Truncated: " << truncated << endl; // 3
// Explicit casting (you control it)
double total = 17.0;
int
...User Input with cin
Build an interactive profile using cin for user input
#include <iostream>
#include <string>
using namespace std;
int main() {
// Reading different types of input
string firstName, lastName;
int birthYear;
double height;
cout << "Enter your first name: ";
cin >> firstName;
cout << "Enter your last name: ";
cin >> lastName;
cout << "Enter your birth year: ";
cin >> birthYear;
cout << "Enter your height (meters): ";
cin >> height;
// Calculate age (approximate)
int curre
...Common Mistakes
⚠️ Using uninitialized variables: In C++, uninitialized variables contain garbage values. Always assign a value before using.
⚠️ Integer division surprise: 7 / 2 gives 3, not 3.5. Use 7.0 / 2 for decimal results.
⚠️ Forgetting #include <string>: The string type requires its own header on some compilers.
⚠️ Mixing up ' and ": Single quotes 'A' are for char, double quotes "A" are for string.
Pro Tips
💡 Prefer double over float: double is the default floating-point type in C++. Only use float when memory is tight.
💡 Use meaningful names: studentAge is better than x. Your future self will thank you.
💡 Initialize everything: Always give variables an initial value, even if it's 0 or "".
📋 Quick Reference
| Concept | Syntax |
|---|---|
| Declare integer | int x = 10; |
| Declare double | double pi = 3.14; |
| Declare string | string name = "Alice"; |
| Constant | const int MAX = 100; |
| Type cast | static_cast<double>(x) |
| Check size | sizeof(int) |
Lesson Complete!
You now know how to store and manipulate data using C++ variables, constants, and type casting. Next up: Operators — learn to perform calculations and make comparisons.
Sign up for free to track which lessons you've completed and get learning reminders.