Type Casting in C++
In C++, type casting means converting one data type into another. It is used when we want to perform operations between different data types or store one type of value in a variable of another type.
For example, when we divide two integers, the result is always an integer. But if we want the result in decimal form, we can convert one of the integers into a float using type casting.
Types of Type Casting
There are mainly two types of type casting in C++:
- Implicit Type Casting (Automatic Conversion)
- Explicit Type Casting (Manual Conversion)
1. Implicit Type Casting (Type Promotion)
This is also known as type promotion. It is done automatically by the compiler when a smaller data type value is assigned to a larger data type.
Example:
#include <iostream>
using namespace std;
int main() {
int num = 10;
float result = num + 2.5; // int is converted to float automatically
cout << "Result = " << result;
return 0;
}
Output:
Result = 12.5
Explanation:
- The integer num is automatically converted to float during addition.
- This process is called implicit type casting.
- It avoids data loss and maintains consistency in calculations.
2. Explicit Type Casting (Manual Conversion)
In explicit type casting, the conversion is done manually by the programmer using casting operators. This allows us to control the conversion process.
Syntax:
(data_type) expression
Example:
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 2;
float result = (float)a / b; // manual conversion
cout << "Result = " << result;
return 0;
}
Output:
Result = 2.5
Explanation:
- The variable a is manually converted into float.
- Now the division is done in floating-point, not integer division.
- This gives the correct decimal result.
Common Type Casting Conversions
| From Type | To Type | Example |
|---|---|---|
| int | float | (float)5 → 5.0 |
| float | int | (int)3.7 → 3 |
| char | int | (int)'A' → 65 |
Summary:
- Type Casting converts data from one type to another.
- Implicit casting is automatic (done by compiler).
- Explicit casting is manual (done by programmer).
- Used to prevent data loss or ensure correct operation results.