A data type in C++ tells the compiler what kind of data a variable can hold.
Each variable in C++ must be declared with a specific type before use.
Why Are Data Types Important?
- Help the compiler allocate memory correctly
- Define what kind of operations can be performed on the variable
- Prevent type-related errors during compilation
Categories of Data Types in C++
| Category | Description |
|---|
| Primary (Built-in) | Basic types like int, char, float, etc. |
| Derived | Based on built-in types, e.g., arrays, pointers, functions |
| User-defined | Created by the user, e.g., struct, class, enum |
| Void | Represents absence of value, mostly used in functions |
1. Primary (Built-in) Data Types
| Type | Size (Typical) | Description | Example |
|---|
int | 4 bytes | Stores integers | int age = 25; |
char | 1 byte | Stores single character | char grade = 'A'; |
float | 4 bytes | Stores decimal numbers | float pi = 3.14; |
double | 8 bytes | More precise decimal | double area = 12.456; |
bool | 1 byte | Stores true/false | bool isValid = true; |
Sizes may vary slightly depending on compiler and system architecture.
2. Derived Data Types
| Type | Description |
|---|
| Array | Collection of elements of same type |
| Pointer | Stores memory address of a variable |
| Function | Function declaration or pointer to function |
| Reference | Alias for another variable |
3. User-defined Data Types
| Type | Purpose |
|---|
struct | Group of variables of different types |
class | Object-oriented data structure |
enum | Defines a set of named integer constants |
union | Shares memory among its members |
typedef | Creates an alias for existing data type |
4. Void Data Type
- Used when a function does not return a value.
void greet() {
cout << "Hello!" << endl;
}
Modifiers with Data Types
| Modifier | Used With | Purpose |
|---|
signed | int, char | Can store positive and negative values |
unsigned | int, char | Only positive values (increases range) |
short | int | Smaller integer size |
long | int, double | Larger size and range |
Example:
unsigned int x = 100;
long double bigValue = 123456.7890;