C Type Conversion
1. What is Type Conversion?
-
Type conversion is the process of converting a value from one data type to another.
-
C supports two types of conversions:
-
Implicit Conversion (Type Promotion)
-
Explicit Conversion (Type Casting)
-
2. Implicit Type Conversion (Type Promotion)
-
Also called automatic type conversion.
-
Happens when C automatically converts a smaller data type to a larger data type to avoid data loss during operations.
Example:
Output:
Here,
int ais promoted to float before addition.
3. Explicit Type Conversion (Type Casting)
-
Done manually by the programmer using type casting operator:
-
Example: Convert float to int
Output:
Note: Type casting truncates the decimal part.
4. Type Conversion in Expressions
-
Mixed data types in expressions are promoted to the larger type automatically.
Output:
-
Without type conversion:
Integer division truncates the result; type casting can fix this:
5. Key Points
-
Implicit conversion: automatic, usually safe, promotes smaller type to larger type.
-
Explicit conversion: manual, can lose data (e.g., float → int).
-
Use casting to ensure correct results in mixed-type expressions.
-
Common casting:
int,float,double,char.
6. Combined Example
Output:
