C++ Type Conversions
Different constant and variables are combined in an expression, then type conversion is used to convert to the same type.
The process of converting one predefined type into another is called type conversion.
There are two type of Type Convserion in C++:
C++ Implicit Type Conversion
An Implicit Type Conversion is also known as Automtic Type Conversion. This type of conversion is performed by the compiler without the intervention of the programmer.
When different data types are mixed in an expression than an Implicit type conversion helps to convert it to the same data type, so there will be no loss of information.
The compiler converts all operands to the type of the largest operand known as type promotion.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
Example of Type Implicit Conversion:
// An example of implicit conversion
// An example of implicit conversion #include <iostream> using namespace std; int main() { int x = 10; // integer x char y = 'a'; // character c // y implicitly converted to int. ASCII // value of 'a' is 97 x = x + y; // x is implicitly converted to float float z = x + 1.0; cout << "x = " << x << endl << "y = " << y << endl << "z = " << z << endl; return 0; }
Output :
x = 107 y = a z = 108
C++ Explicit Type Conversion
An Explicit Type Conversion is also known as User Type Conversion. This type of conversion is performed by the user or programmer who forces an expression to be of a specific type, thus information loss will not occur.
Type casting can be done as:
type(expression) \\where the type is a valid c++ data type
Example :
// C++ program to demonstrate // explicit type casting #include <iostream> using namespace std; int main() { double x = 1.2; // Explicit conversion from double to int int sum = (int)x + 1; cout << "Sum = " << sum; return 0; }
Output :
Sum = 2
C++ Shortands
C++ provides a user specific shorthand that helps user to simplify coding of a certain type of assignment statement.
var = var operator expression
is same as
var operator = expression
Example of Shortands:
x+=5; is equivalent to x=x+5; x-=10; is equivalent to x=x-10; x*=3; is equivalent to x=x*3; x/=2; is equivalent to x=x/2; x%=4; is equivalent to x=x%4;
Exercise:-
1. Which type conversion is known as automatic Type Conversion?
View Answer
2. Which type of conversion is done by the user?
View Answer
Program :-
C++ program to Type Conversion and Type Casting
#include<iostream.h> #include<conio.h> void main() { clrscr(); float res; float f1=15.5, f2=2; res = (int)f1/(int)f2; cout<< res<< endl; res = (int)(f1/f2); cout<< res<< endl; res = f1/f2; cout<< res; getch(); }
Output :
7 7 7.5
Visit :
Discussion