C++ Programming

Variables and Data Types

Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.

On this page

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
int4 bytes-2,147,483,648 to 2,147,483,647
short2 bytes-32,768 to 32,767
long4-8 bytesPlatform dependent
long long8 bytesVery large integers

Example:

1int age = 25;
2short year = 2024;
3long population = 8000000000;

2. Floating-Point Types

Store decimal numbers.

TypeSizePrecision
float4 bytes~7 decimal digits
double8 bytes~15 decimal digits
long double10-16 bytesHighest precision

Example:

1float price = 19.99f;
2double pi = 3.141592653589793;
3long double precise = 3.141592653589793238L;

3. Character Type

Stores single characters.

TypeSizeRange
char1 byte-128 to 127 (or 0 to 255)

Example:

1char grade = 'A';
2char symbol = '@';

4. Boolean Type

Stores true/false values.

TypeSizeValues
bool1 bytetrue or false

Example:

1bool isStudent = true;
2bool isGraduated = false;

Variable Declaration and Initialization

Declaration Only

1int number;  // Declared but not initialized (contains garbage value)

Declaration with Initialization

1int number = 10;        // Traditional initialization
2int count{5};          // Brace initialization (C++11)
3int 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)
1signed int negative = -100;
2unsigned int positive = 100;
3unsigned 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.

1auto number = 42;        // int
2auto price = 19.99;      // double
3auto name = "John";      // const char*
4auto 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

1const int MAX_SIZE = 100;
2const double PI = 3.14159;
3const char NEWLINE = '\n';

constexpr (C++11)

For compile-time constants:

1constexpr int ARRAY_SIZE = 10;
2constexpr double GRAVITY = 9.8;

Type Conversion

Implicit Conversion

Automatic conversion between compatible types:

1int num = 10;
2double decimal = num;  // int automatically converted to double

Explicit Conversion (Casting)

1double price = 19.99;
2int rounded = (int)price;           // C-style cast
3int 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:

1void function() {
2    int local = 10;  // Only accessible in this function
3}

Global Scope

Variables declared outside all functions:

1int global = 100;  // Accessible everywhere
2 
3int main() {
4    cout << global << endl;
5    return 0;
6}

Sizeof Operator

Find the size of a data type or variable:

1cout << sizeof(int) << endl;      // 4
2cout << sizeof(double) << endl;    // 8
3cout << sizeof(char) << endl;      // 1
4 
5int number = 10;
6cout << sizeof(number) << endl;    // 4

Practical Examples

Example 1: Student Information

1string name = "John Doe";
2int age = 20;
3double gpa = 3.75;
4char grade = 'A';
5bool isEnrolled = true;

Example 2: Temperature Conversion

1double celsius = 25.0;
2double 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.

Sample Output

Age: 25
Price: $19.99
Temperature: 98.6°F
Grade: A
Is Student: 1