Courses/C++/Variables & Data Types

    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 type

    C++ Data Types at a Glance

    TypeSizeRangeExample
    int4 bytes-2.1B to 2.1Bint age = 25;
    double8 bytes15 decimal digitsdouble pi = 3.14;
    float4 bytes7 decimal digitsfloat t = 36.6f;
    char1 byteSingle characterchar g = 'A';
    bool1 bytetrue / falsebool ok = true;
    stringvariesAny textstring s = "Hi";

    Basic Data Types

    Declare and print all fundamental C++ data types

    Try it Yourself »
    C++
    #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 version

    Naming 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

    Try it Yourself »
    C++
    #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

    Try it Yourself »
    C++
    #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

    Try it Yourself »
    C++
    #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

    ConceptSyntax
    Declare integerint x = 10;
    Declare doubledouble pi = 3.14;
    Declare stringstring name = "Alice";
    Constantconst int MAX = 100;
    Type caststatic_cast<double>(x)
    Check sizesizeof(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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service