Type Conversion is the conversion of one operand's value to a different data type either implicitly or explicitly. Type conversion may occur when any of the following conditions are met :
- Whenever a value of one type is assigned to a variable of another type.
- When an operator converts the type of its operand(s) before performing operation.
- When a value of one type is explicitly cast to a different type.
- When a value is passed as an argument to a function or is returned from a function.
Type conversion can be either implicit or explicit.
- Implicit/Automatic Type Conversion :
- An expression may consist of operands belonging to different data types. In those expressions, the evaluation is done after the operands are converted to a common data type.
In C, the automatic conversion of the operands is done as follows :
- If either operand is of type long double, the other operand is converted to type long double.
- If the above condition is not met and either operand is of type double, the other operand is converted to type double.
- If the above two conditions are not met and either operand is of type float, the other operand is converted to type float.
- If the above three conditions are not met (none of the operands are of floating types), then integral conversions are performed on the operands as follows:
- If either operand is of type unsigned long, the other operand is converted to type unsigned long.
- If the above condition is not met and either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.
- If the above two conditions are not met, and either operand is of type long, the other operand is converted to type long.
- If the above three conditions are not met, and either operand is of type unsigned int, the other operand is converted to type unsigned int.
- If none of the above conditions are met, both operands are converted to type int.
- Explicit Conversion / Type Casting
- If you want the type conversion that is different from the Implicit conversions, you will have to type casts to explicitly convert types.
It can be done as follows :
(type name) expression
Here type name is the destined data type and expression is the expression is the one that is to be converted to that type.
For example,
Without Type Casting
int x = 5, y=2 ; float result; result = x/y; printf("%f",result);
Output: 2.000000
With Type Casting
int x = 5, y=2 ; float result; result = (float) x/y; printf("%f",result);
Output: 2.500000
No comments:
Post a Comment