Variables and Data Types in C++

9/12/2025
All Articles

Variables Data Types in C++ plus

Variables and Data Types in C++

Variables and Data Types in C++


Introduction

Variables and data types are fundamental building blocks in C++. A variable is a named memory location used to store data, while a data type defines the type of data a variable can hold.


Declaring and Initializing Variables

  • Declaration reserves memory for the variable.

  • Initialization assigns an initial value.

Example:

int age;          // Declaration
age = 25;         // Initialization
int year = 2025;  // Declaration + Initialization

Basic Data Types in C++

Data Type Description Example
int Stores integers (whole numbers) int x = 10;
float Stores single-precision floating-point numbers float pi = 3.14;
double Stores double-precision floating-point numbers double g = 9.81;
char Stores single characters char grade = 'A';
bool Stores Boolean values (true/false) bool isReady = true;
void Represents no value (used in functions) void greet() {}

Type Modifiers

  • Modify the size and range of basic data types.

  • Common modifiers: signed, unsigned, short, long

Example:

unsigned int age = 30;
long long distance = 1234567890;

Rules for Naming Variables

  • Must start with a letter or underscore _

  • Can contain letters, digits, and underscores

  • Cannot use C++ keywords (int, if, return, etc.)

  • Case-sensitive (Age and age are different)


Type Inference using auto

  • auto lets the compiler deduce the variable’s type.

Example:

auto price = 99.99;  // Automatically becomes double
auto name = "John";  // Automatically becomes const char*

Example Program

#include <iostream>
using namespace std;

int main() {
    int age = 25;
    float pi = 3.14;
    char grade = 'A';
    bool isReady = true;

    cout << "Age: " << age << endl;
    cout << "Pi: " << pi << endl;
    cout << "Grade: " << grade << endl;
    cout << "Ready: " << isReady << endl;

    return 0;
}

Output:

Age: 25
Pi: 3.14
Grade: A
Ready: 1

Summary

  • Variables store data values, and data types define the type of data.

  • Use proper data types and modifiers to save memory and improve performance.

  • auto keyword helps simplify type declarations.

Article