C++ Data Types
Data types in C++ are categorized into various types based on their functionality and characteristics. Here are the main data types:
1. Primitive Data Types
These are the basic data types in C++:
- int: Used to store integers (whole numbers). Example:
int age = 25;
- float: Used to store floating-point numbers (numbers with a decimal point). Example:
float weight = 72.5;
- double: Similar to
float
but with double precision. Example: double pi = 3.14159;
- char: Used to store a single character. Example:
char grade = 'A';
- bool: Used to store boolean values (
true
or false
). Example: bool isStudent = true;
- void: Represents the absence of type. Typically used for functions that do not return a value. Example:
void functionName();
2. Derived Data Types
These data types are derived from the primitive data types:
- Arrays: Collection of elements of the same type. Example:
int numbers[5] = {1, 2, 3, 4, 5};
- Pointers: Used to store the address of another variable. Example:
int* ptr = &age;
- References: An alias for another variable. Example:
int& ref = age;
3. User-defined Data Types
These data types are defined by the user to create complex data structures:
- Structures: Used to group different types of data. Example:
struct Person { string name; int age; };
- Unions: Similar to structures but members share the same memory location. Example:
union Data { int i; float f; }
- Enums: Used to define a set of named integer constants. Example:
enum Color { RED, GREEN, BLUE };
- Classes: Used to define objects with attributes and methods. Example:
class Car { public: string brand; int speed; };