Explanation: In this code, implicit type conversion occurs when n1 (int) is automatically converted to a float during the expression n1 + n2 to match the type of n2.
Note: It is possible for type conversions to lose information. Signs can be lost when signed is implicitly converted to unsigned, and overflow can occur when long is converted to float.
When Implicit Type Conversion Occurs?
Implicit type conversion happens according to conversion rank, where higher-priority types are only converted to lower-priority types when needed.
It occurs in assignment expressions, e.g., assigning a float to an int truncates the decimal part.
It happens in binary operators, where operands of different types are converted to a common type for the operation.
It involves promotion, converting a smaller data type to a larger one (e.g., int to float) to prevent data loss.
It can involve demotion, converting a larger data type to a smaller one (e.g., float to int), which may cause loss of precision.
Explicit Type Conversion
Explicit type conversion is when the programmer manually converts a variable from one data type to another.
It is done using a type cast operator (type) before the value.
Used to force conversion when automatic (implicit) conversion doesn’t happen or isn’t desired.
Can convert larger types to smaller types or smaller types to larger types, but converting to smaller types may cause data loss or truncation.
Output
7
Explanation: In this example, the float n1 is manually cast to an integer using (int)n1. This conversion truncates the decimal part, resulting in the integer value being assigned to n2.