02

Module 2: Variables and Data Types

Chapter 2 • Beginner

30 min

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).

TypeSizeRange
`int`4 bytes-2,147,483,648 to 2,147,483,647
`short`2 bytes-32,768 to 32,767
`long`4-8 bytesPlatform dependent
`long long`8 bytesVery large integers

Example:

cpp.js
int age = 25;
short year = 2024;
long population = 8000000000;

2. Floating-Point Types

Store decimal numbers.

TypeSizePrecision
`float`4 bytes~7 decimal digits
`double`8 bytes~15 decimal digits
`long double`10-16 bytesHighest precision

Example:

cpp.js
float price = 19.99f;
double pi = 3.141592653589793;
long double precise = 3.141592653589793238L;

3. Character Type

Stores single characters.

TypeSizeRange
`char`1 byte-128 to 127 (or 0 to 255)

Example:

cpp.js
char grade = 'A';
char symbol = '@';

4. Boolean Type

Stores true/false values.

TypeSizeValues
`bool`1 byte`true` or `false`

Example:

cpp.js
bool isStudent = true;
bool isGraduated = false;

Variable Declaration and Initialization

Declaration Only

cpp.js
int number;  // Declared but not initialized (contains garbage value)

Declaration with Initialization

cpp.js
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)
cpp.js
signed int negative = -100;
unsigned int positive = 100;
unsigned char byte = 255;

Size Modifiers

  • short: Smaller size
  • long: Larger size
  • long long: Even larger

Type Deduction (C++11)

auto Keyword

The auto keyword lets the compiler deduce the type automatically.

cpp.js
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

cpp.js
const int MAX_SIZE = 100;
const double PI = 3.14159;
const char NEWLINE = '\n';

constexpr (C++11)

For compile-time constants:

cpp.js
constexpr int ARRAY_SIZE = 10;
constexpr double GRAVITY = 9.8;

Type Conversion

Implicit Conversion

Automatic conversion between compatible types:

cpp.js
int num = 10;
double decimal = num;  // int automatically converted to double

Explicit Conversion (Casting)

cpp.js
double price = 19.99;
int rounded = (int)price;           // C-style cast
int rounded2 = static_cast<int>(price);  // C++ style (preferred)

Common Variable Naming Conventions

  1. camelCase: firstName, totalAmount
  2. snake_case: first_name, total_amount
  3. 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:

cpp.js
void function() {
    int local = 10;  // Only accessible in this function
}

Global Scope

Variables declared outside all functions:

cpp.js
int global = 100;  // Accessible everywhere

int main() {
    cout << global << endl;
    return 0;
}

Sizeof Operator

Find the size of a data type or variable:

cpp.js
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

cpp.js
string name = "John Doe";
int age = 20;
double gpa = 3.75;
char grade = 'A';
bool isEnrolled = true;

Example 2: Temperature Conversion

cpp.js
double celsius = 25.0;
double fahrenheit = (celsius * 9.0 / 5.0) + 32.0;

Best Practices

  1. Always initialize variables
  2. Use meaningful names (userAge not x)
  3. Choose appropriate types (use int for whole numbers, not double)
  4. Use `const` for values that don't change
  5. Avoid global variables when possible
  6. 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.