Type conversion can be done in 2 ways in C ++
1. Implicit type conversion
2. Explicit type conversion
- Implicit type conversion
- The implicit type conversion is the type of conversion done automatically by the compiler without any human effort.
- It means, implicit conversion automatically converts one data type into another data type based on some pre-defined rules.
- It is also known as automatic type conversion.
- order of typecast in implicit conversion :
Boolà charà short intà intà unsigned intà long intà unsigned long intà long long intà floatà double à long double.
- Means in implicit conversion small data type value is converted in form big data type automatically by the compiler.
Example program:
#include<iostream>
using namespace std;
int main(){
int a = 'A'; // char to int
cout<<a; // 65
return 0;
}
2. Explicit type conversion
Conversion that requires user interaction to change the data type is called explicit type conversion in other words explicit type conversion allows programmer to manually change or type casting data type of the data into another data type.
(Basically here we convert the big data type into small data type)
Syntax :
(type)expression
Flow of data type in explicit type conversion:
long double ➡️ double ➡️
float ➡️ long long int ➡️ unsigned long int ➡️
long int ➡️ unsigned int ➡️ int ➡️
short int ➡️ char ➡️ char ➡️
bool
#include<iostream>
using namespace std;
int main(){
char s = (char)65; // int to char
cout<<s; // A
return 0;
}