Type casting or type conversion is a technique which is used to convert the value of one predefined data type into another data type, typically will change size or interpretation property. The size may widen or narrow.
Rules when performing arithmetic operations on data:
1. Implicit conversion or Automatic conversion: In this type of conversion we do not need to specify a data type, it automatically assigns a value of one data type into another. Assigning a smaller data type into a larger data type is known as Implicit conversion. Loss of value is not possible in Implicit conversion.
int a = 10; float b = a; //type casting
Example 1: WAP to explain the use of Implicit/Automatic conversion.
void main() { int a=10, b=4; float c; clrscr(); c=a/b; //implicit conversion: convert result into float cout<<"After Implicit Conversion = "<<c; getch(); }
2. Explicit conversion or Forcefully conversion: In this type of conversion, we need to place the name of the desired data type in the parentheses immediately before the value to be converted. Assigning a larger data type value into a smaller data type is known as explicit conversion. In explicit conversion, loss of value may be possible.
float x = 10.5; int y = (int)x;
Example 2: WAP to explain the use of Explicit conversion.
void main() { int a=10, b=4; float c; clrscr(); c=(float)a/b; //explicit conversion: convert a into float then put result in c. cout<<"After Explicit Conversion = %f"<<c; getch(); }