Data Types in C++

Data types define the nature of data that can be stored and manipulated in a program.

Primary (Built-in) Data Types

General Syntax:

data_type variable_name = value;

Example:

int age = 25;

float pi = 3.14;

char grade = ‘A’;

bool isValid = true;

Derived Data Types

Derived types are constructed from built-in types. These include:

  1. Array: Collection of elements of the same type.

Example: int numbers[5] = {1, 2, 3, 4, 5};

  1. Function: A block of code that performs a specific task.

Example: int add(int a, int b) { return a + b; }

  1. Pointer: Stores the memory address of another variable.

Example: int *ptr = &age;

  1. Reference: Provides an alias for a variable.

Example: int& ref = age;

User-Defined Data Types

Users can define their own data types using:

  1. Structure (struct): Combines different data types.

Example:

struct Student {

int id;

char name[30];  };

 

  1. Union (union): Shares memory between variables.

Example:

union Data {

int i;

float f;  };

 

  1. Enumeration (enum): Defines a set of named constants.

Example:

enum Color {

RED, GREEN, BLUE  };

 

  1. Class: Defines objects with data and functions.

Example:

class Car {

public: int speed;

void drive(); };