Data types in C++ define the type of data a variable can store. They help the compiler understand how much memory to allocate and what kind of operations can be performed on the data.
What are Data Types?
A data type specifies:
- The kind of value a variable can hold
- The size of memory required
- The operations allowed on that data
Example:
int age = 18;
Here, int is the data type.
Types of Data Types in C++
C++ data types are mainly divided into:
- Basic (Primitive) Data Types
- Derived Data Types
- User-Defined Data Types
Basic Data Types
int
Used to store whole numbers.
int number = 10;
float
Used to store decimal values.
float price = 99.5;
double
Used to store large decimal numbers with more precision.
double value = 123.456789;
char
Used to store a single character.
char grade = 'A';
bool
Used to store true or false values.
bool isPassed = true;
string
Used to store text.
string name = "Ali";
Example Program
#include <iostream>
using namespace std;
int main() {
int age = 18;
float marks = 85.5;
char grade = 'A';
bool passed = true;
cout << age << endl;
cout << marks << endl;
cout << grade << endl;
cout << passed << endl;
return 0;
}
Output
18
85.5
A
1
Derived Data Types
Derived data types are created from basic data types.
Examples:
- Arrays
- Pointers
- Functions
Example:
int numbers[5];
User-Defined Data Types
These are created by the programmer.
Examples:
- Structures
- Classes
- Enumerations
Example:
struct Student {
string name;
int age;
};
Size of Common Data Types
| Data Type | Typical Size |
|---|---|
| int | 4 bytes |
| float | 4 bytes |
| double | 8 bytes |
| char | 1 byte |
| bool | 1 byte |
Why Data Types are Important
Data types are important because they:
- Define memory usage
- Improve program efficiency
- Prevent invalid operations
- Help organize data correctly
Real-Life Example
- int → Number of students
- float → Product price
- char → Grade letter
- bool → Pass or fail status
- string → Person name
Conclusion
Data types are a fundamental part of C++ programming. They define what kind of data can be stored and processed in a program. Understanding data types helps write efficient, accurate, and organized code.