Type Casting
Type Casting
Converting one type of data into another type of data is called as type conversion. What happens when we write an expression that involves two different types of data, such as multiplying an integer and a floating point number? To perform these evaluations, one of the types must be converted.
There are two types of Type conversions:
1) Implicit type conversion
2) Explicit type conversion
Implicit type conversion:
When the types of the two operands in a binary expression are different, C automatically converts one type to another. This is known as implicit type conversion.
Example:
char c = „A‟; int i = 1234; long double d = 3458.0004; i = c; // since i is integer type C automatically converts c=‟A‟ as c = 65 and then assigns 65 to i d = i; // since d is long double, value of i is converted to 1234.0 and it is assigned to d. X = d + i; // X = double + int is converted to X = double + double, since d and i are of two different types(int is promoted to long double type), therefore result of X is 4692.0004(3458.0004 + 1234.0)
Explicit type conversion:
Rather than let the compiler implicitly convert data, we can convert data from one type to another ours self using explicit type conversion. Explicit type conversion uses the unary cast operator, which has a precedence of 14.
To cast data from one type to another, we specify the new type in parentheses before the value we want to be converted.
For example,
To convert an integer A to a float, we code the expression as given below
(float) A
One use of the cast operator is to ensure that the result of a divide is a real number. For example, if we calculated ratio of girls and boys (both are integer values) in a class without a cast operator, then the result would be an integer value. So to force the result in fractional form, we cast calculation as shown below.
Ratio = (float) No_of_Girls / No_of_Boys;
Or
Ratio = No_of_Girls / (float) No_of_Boys;