Type Conversion:
Type conversion is the process of converting one data type into another. In C, it can happen implicitly (automatically by the compiler) or explicitly (manually by the programmer).
Implicit Type Conversion:
This occurs when the compiler automatically converts one type to another without any explicit instruction from the programmer. For example:
int num_int = 10; float num_float = num_int; // Implicit conversion from int to float
int
value 10
is implicitly converted to a float
when assigned to num_float
. This is allowed because a float can accommodate an integer value without loss of precision.Explicit Type Conversion (Type Casting):
Type casting is the explicit conversion of a variable from one data type to another. It's done by placing the desired data type in parentheses before the variable to be converted. For example:
float num_float = 10.5; int num_int = (int)num_float; // Explicit conversion from float to int
num_float
is explicitly cast to an int
type using (int)
. This operation results in num_int
having the integer part of the num_float
, effectively truncating the decimal part.(int)
tells the compiler to treatnum_float
as anint
.- The decimal part of
num_float
is discarded, and only the integer part is assigned tonum_int
. num_int
now contains the value10
.
- Type casting can lead to loss of data or precision, especially when converting from a larger data type to a smaller one.
- It's important to be cautious when performing type casting to avoid unintended consequences like data loss.