C++ Type Conversion
Type Conversion in C++ is a way to convert data type of one variable to another data type. Like convert float to int or int to float etc.; it is also called as type casting. It provides the facility to change the data type of one variable to another type. C++ Type Conversion is of two types such as Implicit Type Conversion (done automatically by the complier), and Explicit Type Conversion (done by the programmer).
int a = (int)2.5; // Explicit type conversion
At eitworld.com you can learn Type Conversion in C++ in simple ways with lot of examples.
- Type conversion is a way to convert data type of a variable to another data type. Like convert float to int or int to float etc.; it is also called as type casting. It provides the facility to change the data type of one variable to another type.
- In C++ type conversion can be done in two ways: 1) Implicit Type Conversion
2) Explicit Type Conversion
Implicit Type Conversion
- Implicit type conversion is done automatically by the complier. In this type of conversion compiler internally converts the type of variable depending upon the expression.
- Implicit type conversion is further divided into two parts: (a) Conversion During assignment
(b) Arithmetic conversion
- Implicit conversion is done when we assign value of one lower data type to another compatible higher data type.
- Here is an example of this type of implicit type conversion:
char c = 'a';
i = c; /* i is assigned the ASCII code of 'a' */ }
- If two operands of a binary operators are not the same type, then arithmetic implicit conversion is applied by the compiler. Here is an example of implicit arithmetic conversion:
float b=2.5, c;
Explicit Type Conversion
- In Explicit type conversion we have to explicitly convert the data type of a variable into another data type.
- It is also known as type casting. Which takes cast "()" operator for type conversion.
- The basic syntax of explicit type conversion is as follows:
- Here are some examples of explicit type conversion:
float j, k=3.14;
j = (float) i; /*j= 10.0 */
I = (int) k; /*I = 3 */
I = (int (-k) /*i=-3 */