Learn type casting in C++ with simple explanations and examples. Understand implicit and explicit casting, conversion between int and float, and how C++ handles data type conversion in programs.
Type casting means converting a value from one data type to another data type.
For example:
int x = 10;
double y = x;
Here, int is converted to double.
int → double
There are two basic types:
Implicit casting happens automatically.
The compiler performs the conversion without being told.
int x = 10;
double y = x;
cout << y;
10
Here:
int → double
The compiler automatically converts 10 into 10.0.
Implicit = Automatic
Explicit casting is done by the programmer.
The programmer tells C++ which data type to convert the value into.
double x = 10.75;
int y = (int)x;
cout << y;
10
Here:
double → int
The decimal part .75 is removed.
Explicit = Programmer tells C++
int a = 5;
int b = 2;
double result = (double)a / b;
cout << result;
2.5
The programmer explicitly converts a:
int → double
So the calculation becomes:
5.0 / 2 = 2.5
| Implicit Casting | Explicit Casting |
|---|---|
| Automatic | Done by programmer |
| Compiler performs conversion | Programmer specifies conversion |
| No special casting syntax | Casting syntax is used |
double y = x; |
int y = (int)x; |
Example: int → double |
Example: double → int |
int to double#include <iostream>
using namespace std;
int main() {
int num = 10;
double result = num;
cout << result;
return 0;
}
Output:
10
Understand the Code:
num is an int.result is a double.int to double.double to int#include <iostream>
using namespace std;
int main() {
double num = 15.75;
int result = (int)num;
cout << result;
return 0;
}
Output:
15
Understand the Code:
num contains 15.75.(int)num converts it to an integer..75 is removed.#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 2;
double result = (double)a / b;
cout << result;
return 0;
}
Output:
2.5
Understand the Code:
5 / 2 gives 2 because both values are integers.(double)a converts 5 into 5.0.5.0 / 2.2.5.Implicit casting: C++ does it automatically.
Explicit casting: The programmer does it using:
(type)value
Example:
(double)a
(int)num