Module 2: Variables and Data Types
Chapter 2 • Beginner
Variables and Data Types
Variables are containers that store data in memory. In C++, you must declare the type of data a variable will hold before using it.
What are Variables?
A variable is a named storage location in memory that holds a value. Think of it as a labeled box where you can store different types of information.
Key Concepts:
- Declaration: Telling the compiler about a variable's name and type
- Initialization: Giving a variable its first value
- Assignment: Changing a variable's value
Fundamental Data Types
C++ provides several built-in data types:
1. Integer Types
Store whole numbers (no decimal points).
| Type | Size | Range |
|---|---|---|
| `int` | 4 bytes | -2,147,483,648 to 2,147,483,647 |
| `short` | 2 bytes | -32,768 to 32,767 |
| `long` | 4-8 bytes | Platform dependent |
| `long long` | 8 bytes | Very large integers |
Example:
int age = 25;
short year = 2024;
long population = 8000000000;
2. Floating-Point Types
Store decimal numbers.
| Type | Size | Precision |
|---|---|---|
| `float` | 4 bytes | ~7 decimal digits |
| `double` | 8 bytes | ~15 decimal digits |
| `long double` | 10-16 bytes | Highest precision |
Example:
float price = 19.99f;
double pi = 3.141592653589793;
long double precise = 3.141592653589793238L;
3. Character Type
Stores single characters.
| Type | Size | Range |
|---|---|---|
| `char` | 1 byte | -128 to 127 (or 0 to 255) |
Example:
char grade = 'A';
char symbol = '@';
4. Boolean Type
Stores true/false values.
| Type | Size | Values |
|---|---|---|
| `bool` | 1 byte | `true` or `false` |
Example:
bool isStudent = true;
bool isGraduated = false;
Variable Declaration and Initialization
Declaration Only
int number; // Declared but not initialized (contains garbage value)
Declaration with Initialization
int number = 10; // Traditional initialization
int count{5}; // Brace initialization (C++11)
int value = {20}; // Brace initialization with =
Best Practice: Always initialize variables when declaring them!
Type Modifiers
Modifiers change the meaning of base types:
Signed/Unsigned
signed: Can hold positive and negative values (default)unsigned: Only positive values (doubles positive range)
signed int negative = -100;
unsigned int positive = 100;
unsigned char byte = 255;
Size Modifiers
short: Smaller sizelong: Larger sizelong long: Even larger
Type Deduction (C++11)
auto Keyword
The auto keyword lets the compiler deduce the type automatically.
auto number = 42; // int
auto price = 19.99; // double
auto name = "John"; // const char*
auto isActive = true; // bool
Use `auto` when:
- Type is obvious from initialization
- Working with complex types (iterators, templates)
- Reduces verbosity
Avoid `auto` when:
- Type clarity is important for readability
- Working with beginners who need to see types
Constants
Constants are variables whose values cannot change after initialization.
const Keyword
const int MAX_SIZE = 100;
const double PI = 3.14159;
const char NEWLINE = '\n';
constexpr (C++11)
For compile-time constants:
constexpr int ARRAY_SIZE = 10;
constexpr double GRAVITY = 9.8;
Type Conversion
Implicit Conversion
Automatic conversion between compatible types:
int num = 10;
double decimal = num; // int automatically converted to double
Explicit Conversion (Casting)
double price = 19.99;
int rounded = (int)price; // C-style cast
int rounded2 = static_cast<int>(price); // C++ style (preferred)
Common Variable Naming Conventions
- camelCase:
firstName,totalAmount - snake_case:
first_name,total_amount - PascalCase:
FirstName,TotalAmount(usually for classes)
Rules:
- Must start with letter or underscore
- Can contain letters, digits, underscores
- Cannot use C++ keywords (int, if, for, etc.)
- Case-sensitive
Scope of Variables
Local Scope
Variables declared inside a function:
void function() {
int local = 10; // Only accessible in this function
}
Global Scope
Variables declared outside all functions:
int global = 100; // Accessible everywhere
int main() {
cout << global << endl;
return 0;
}
Sizeof Operator
Find the size of a data type or variable:
cout << sizeof(int) << endl; // 4
cout << sizeof(double) << endl; // 8
cout << sizeof(char) << endl; // 1
int number = 10;
cout << sizeof(number) << endl; // 4
Practical Examples
Example 1: Student Information
string name = "John Doe";
int age = 20;
double gpa = 3.75;
char grade = 'A';
bool isEnrolled = true;
Example 2: Temperature Conversion
double celsius = 25.0;
double fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
Best Practices
- ✅ Always initialize variables
- ✅ Use meaningful names (
userAgenotx) - ✅ Choose appropriate types (use
intfor whole numbers, notdouble) - ✅ Use `const` for values that don't change
- ✅ Avoid global variables when possible
- ✅ Use modern C++ initialization (
{}braces)
Common Errors
- ❌ Using uninitialized variables
- ❌ Type mismatch (assigning double to int without cast)
- ❌ Forgetting semicolons
- ❌ Using wrong type for the data
Next Module
In Module 3, we'll learn about Operators and Expressions - how to perform calculations and manipulate data in C++!
Hands-on Examples
Basic Variable Declaration
#include <iostream>
using namespace std;
int main() {
// Integer
int age = 25;
// Floating point
double price = 19.99;
float temperature = 98.6f;
// Character
char grade = 'A';
// Boolean
bool isStudent = true;
// Display values
cout << "Age: " << age << endl;
cout << "Price: $" << price << endl;
cout << "Temperature: " << temperature << "°F" << endl;
cout << "Grade: " << grade << endl;
cout << "Is Student: " << isStudent << endl;
return 0;
}This example shows how to declare and initialize variables of different types. Each variable type stores different kinds of data: integers for whole numbers, doubles/floats for decimals, char for single characters, and bool for true/false values.
Practice with Programs
Reinforce your learning with hands-on practice programs