Introduction

Variables are fundamental in programming as they store data that can be manipulated and used throughout a program. In C++, variables have specific data types that define the kind of values they hold. Understanding variables and data types is essential for writing efficient and error-free programs.

What is a Variable?

A variable is a named memory location that stores data.

Example:

#include <iostream>
using namespace std;

int main() {
    int age = 25;
    cout << "Your age is: " << age << endl;
    return 0;
}

Explanation:

  • int age = 25; declares a variable named age of type int (integer) and assigns it the value 25.
  • cout prints the stored value to the screen.

Real-Life Analogy:

Think of a variable as a locker in a school. The locker (variable) has a number (name) and contains books (data). You can replace or retrieve books just like updating or accessing a variable’s value.

Naming Rules for Variables

  • Must begin with a letter or underscore (_).
  • Can contain letters, digits, and underscores.
  • Cannot be a C++ keyword (int, float, return, etc.).
  • Case-sensitive (Age and age are different variables).

Valid vs. Invalid Variable Names:

ValidInvalid
userName1stName (starts with a digit)
_totalSumfloat (keyword)
score_100user-name (contains -)

Data Types in C++

Data types specify the kind of data a variable can hold. The main types are:

1. Integer (int)

Stores whole numbers (positive, negative, zero).

int apples = 10;
cout << "Number of apples: " << apples << endl;
  • Size: Typically 4 bytes (varies by system).
  • Range: -2,147,483,648 to 2,147,483,647 (on 32-bit systems).

2. Floating Point (float, double)

Stores decimal numbers.

float price = 9.99;
double distance = 12.3456789;
cout << "Price: " << price << ", Distance: " << distance << endl;
  • float (4 bytes, up to 7 decimal places).
  • double (8 bytes, up to 15 decimal places).

3. Character (char)

Stores single characters (letters, digits, symbols).

char grade = 'A';
cout << "Your grade: " << grade << endl;
  • Size: 1 byte.
  • Stored using ASCII values (e.g., 'A' = 65 in ASCII).

4. Boolean (bool)

Stores true/false values.

bool isRaining = false;
cout << "Is it raining? " << isRaining << endl;
  • Stored as 0 (false) or 1 (true).

5. String (string)

Stores text sequences (requires <string> header).

#include <string>
string name = "Alice";
cout << "Hello, " << name << "!" << endl;
  • More flexible than char for handling text.

6. Wide Character (wchar_t)

Stores Unicode characters (useful for non-English languages).

wchar_t symbol = L'Ω';
wcout << L"Greek Symbol: " << symbol << endl;
  • Requires #include <cwchar> and wcout.

Type Modifiers

C++ allows modifiers to change a data type’s properties.

Common Modifiers:

ModifierExampleMeaning
signedsigned int x;Default, stores both positive & negative numbers
unsignedunsigned int x;Stores only positive numbers, doubles max range
shortshort int x;Uses less memory (2 bytes)
longlong int x;Stores larger numbers (8 bytes)

Example:

unsigned int population = 5000000;
cout << "City population: " << population << endl;
  • unsigned int ensures only non-negative numbers.

Type Conversion (Casting)

Sometimes, we need to convert a variable from one type to another.

Implicit Conversion (Automatic)

C++ automatically converts types when necessary.

int num = 10;
double result = num + 2.5; // `int` converted to `double`
cout << result; // Output: 12.5

Explicit Conversion (Casting)

For manual conversion, use casting:

double pi = 3.1416;
int approx = (int)pi; // Convert to int
cout << approx; // Output: 3

Best Practices for Using Variables

✔️ Use meaningful names (totalMarks instead of x).

✔️ Choose the correct data type to save memory.

✔️ Initialize variables before use.

✔️ Prefer const for constant values (const double PI = 3.1416;).

✔️ Avoid unnecessary type conversions.

Conclusion

Understanding variables and data types is crucial in C++. We covered:

  • What variables are and how to declare them.
  • Different data types (int, float, char, bool, string).
  • Type modifiers (unsigned, long, etc.).
  • Type conversion techniques.

Next, we’ll explore Operators in C++, which allow us to perform calculations and logical operations!