Explicit type conversion in C, also known as typecasting, is the process of converting one data type to
another by explicitly specifying the target type. This is different from implicit type conversion, where
the conversion is done automatically by the compiler.
Explicit type conversion is used when we want to convert a value of one type to another type, and we want
to control the way the conversion is done. It is often used to avoid loss of data during a conversion or to
perform operations on values of different types.
In C, explicit type conversion can be done using the cast operator, which has the following syntax:
(type)expression
Here, 'type' is the target data type, and 'expression' is the value that needs to be
converted. The cast operator can be used to convert any compatible data type to any other compatible
data type.
One of the main reasons for using explicit type conversion is to avoid data loss during a
conversion. For example, if we want to convert a float9ing-point value to an integer value,
we can use explicit type conversion to round the floating-point value to the nearest integer:
float f = 3.14;
int i= (int) f;
Here, the float value '3.14' is converted to an integer value using the cast operator,
and the result is stored in the integer variable 'i'. The value of 'i' will be '3',
which is the nearest integer to '3.14'.
Another example of explicit type conversion is when we want to perform arithmetic operations
on values of different types. For example, if we want to add an integer and a floating-point value,
we can use explicit type conversion to convert the integer to a floating-point value before
performing the addition:
int i = 10;
float f = 3.14;
float sum = (float)i+f;
Here, the integer value '10' is converted to a floating-point value using the cast
operator, and then added to the float value '3.14'. The result of the addition is
stored in the float variable 'sum'.
Explicit type conversion is also used when we want to assign a value of one type to a
variable of another type. For example, if we want to assign a character value to an
integer variable, we can use explicit type conversion:
char c ='A';
int i = (int) c;
Here, the character value 'A' is converted to an integer value using the cast operator,
and the result is stored in the integer variable 'i'.
In summary, explicit type conversion in C is a powerful tool for controlling the way data
types are converted in expressions and statements. It allows us to perform operations on
values of different types, avoid data loss during conversions, and convert values to
compatible data types for assignment and other operations.