Lesson 3 of 25

Variables & Data Types

Basic Data Types

C++ has several fundamental data types for storing different kinds of values.

Example
#include <iostream>
using namespace std;

int main() {
    // Integer types
    int age = 25;
    short small = 100;
    long big = 1000000L;
    long long veryBig = 9000000000LL;

    // Floating point
    float price = 9.99f;
    double pi = 3.14159265;

    // Character and Boolean
    char letter = 'A';
    bool isActive = true;

    // Auto type deduction (C++11)
    auto count = 42;       // int
    auto name = "Alice";   // const char*

    // Constants
    const double TAX_RATE = 0.08;
    // TAX_RATE = 0.10; // Error!

    return 0;
}

Type Casting and sizeof

C++ supports both implicit and explicit type conversions. Use sizeof to check the size of types.

Example
// Implicit casting (widening)
int x = 10;
double y = x;  // 10.0

// Explicit casting (narrowing)
double pi = 3.14;
int rounded = (int)pi;              // C-style cast: 3
int rounded2 = static_cast<int>(pi); // C++ style: 3

// sizeof operator
cout << sizeof(int) << endl;    // 4 bytes
cout << sizeof(double) << endl; // 8 bytes
cout << sizeof(char) << endl;   // 1 byte
cout << sizeof(bool) << endl;   // 1 byte