Variables and Data Types in C++

9/12/2025

Variables Data Types in C++ plus

Go Back

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.


 Variables  Data Types in C++ plus

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 TypeDescriptionExample
intStores integers (whole numbers)int x = 10;
floatStores single-precision floating-point numbersfloat pi = 3.14;
doubleStores double-precision floating-point numbersdouble g = 9.81;
charStores single characterschar grade = 'A';
boolStores Boolean values (true/false)bool isReady = true;
voidRepresents 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.