📦 Lesson 3: Variables & Data Types
⏱️ Estimated time: 25 minutes | Difficulty: Beginner
Data Storage
In C++, every variable must have a declared type, allowing the compiler to optimize memory usage.
C++ Data Types
#include <iostream>
#include <string>
using namespace std;
int main() {
// Basic types
int age = 25;
double pi = 3.14159;
float temp = 36.6f;
char grade = 'A';
bool isActive = true;
string name = "Alice"; // C++ string (not char array!)
// Auto type deduction (C++11)
auto x = 42; // int
auto y = 3.14; // double
auto msg = "hello"s; // string (with s suffix)
// Constants
const int MAX_SIZE = 100;
// MAX_SIZE = 200; // Error! Can't change a const
cout << name << " is " << age << " years old" << endl;
cout << "Active: " << boolalpha << isActive << endl;
return 0;
}
Type Casting
// C-style cast
int a = (int)3.14; // 3
// C++ style casts (preferred)
double d = 3.14;
int b = static_cast<int>(d); // 3
// String to number
string numStr = "42";
int num = stoi(numStr); // String to int
double dbl = stod("3.14"); // String to double
// Number to string
string s = to_string(42); // "42"
References
int original = 10;
int &ref = original; // ref IS original
ref = 20;
cout << original; // 20 (changed through reference!)
✅ Quick Quiz
❓ What does 'auto' do in C++?
❓ What is string in C++ (compared to C)?
❓ What does a reference (&) do?