Type Conversion in C++
Type Casting
By- Vatsal Agarwal
Type conversion means conversion of data of one type to another.
In C++ , there are two types of type conversion
1. Implicit Conversion
2. Explicit Conversion
Now before heading to the details of the two types of type conversion, let us know what is Order of Precedence of operators in C++
--> The order of precedence of operators is quite similar to the BODMAS rule in mathematics where the brackets are solved first before 'of' , division is done before multiplication and so on.......
--> Here(in C++) also, increment operator '++' is operated before binary addition operator '+' , Bitwise operators before Logical operators and so on......
a) Implicit Type Conversion
Also known as automatic type conversion.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data (i.e the resulting data type would be the data type that lies above in the precedence order)
Example:
int a = 10;
char c = 'A';
int b = a+c;
Here b will be equal to 75
(because char is implicitly converted to int and ASCII value of A is 65)
b) Explicit Type Conversion
Also called type casting, the method is user-defined. Here the user can typecast the result to make it of a particular data type.
(It means that we can explicitly obtain the data type that we desire)
Example:
int a = 10;
int c = 65;
char b = (char)c + a;
Here b will be equal to K
(because here c is explicitly converted to char type and 65 is ASCII value of A and 65+10=75 and the ASCII value 75 is represented by K)
Advantages of Type Conversion:
- This is done to take advantage of certain features of type hierarchies or type representations.
- It helps to compute expressions containing variables of different data types.
Comments
Post a Comment