Type conversion is the process of converting a value from one data type to another data type. It is useful when different data types are used together in an expression.
Type conversion is the process of converting a value from one data type to another data type. It is useful when different data types are used together in an expression.
An integer value can be converted into a floating-point value:
int a = 10; โ 10.0
Type conversion in C is commonly understood in two ways: Implicit Type Conversion and Explicit Type Conversion.
Implicit type conversion happens automatically by the compiler when values of different data types are used together. The programmer does not explicitly specify the conversion.
Here, a is automatically converted to a floating-point
value before the addition, so the result can be stored in
float.
Explicit type conversion is performed when the programmer deliberately converts a value into another data type using a type cast.
Here, (float)a explicitly converts a
into a floating-point value, so the division produces
2.5.
The basic syntax for explicit type casting is:
float x = (float)10;
The integer value 10 is explicitly converted to
float.
Type conversion is needed when different types of values must be used together or when the result is required in a particular data type.
Type casting is used here so that the average is calculated as
2.5 instead of integer division giving 2.
| Feature | Implicit | Explicit |
|---|---|---|
| Performed by | Compiler | Programmer |
| Specified by programmer? | No | Yes |
| Syntax | No special syntax required | (data_type) |
| Example | float x = 10; |
float x = (float)10; |
When two integer operands are divided using /,
the result is an integer. The fractional part is not retained.
Output: 2
To obtain a decimal result, one operand can be explicitly converted
to float.
Output: 2.5
When a value is converted from a data type that can represent more information to one that can represent less information, some data may be lost.
The fractional part is not retained, so y becomes
10.
| Concept | Remember |
|---|---|
| Type Conversion | Changing a value from one data type to another. |
| Implicit | Conversion performed automatically. |
| Explicit | Conversion performed by the programmer. |
| Type Casting | Explicit conversion using (data_type). |
| Integer Division | Integer รท Integer gives an integer result. |
| Data Loss | Can occur when converting to a less precise type. |
Watch a beginner-friendly explanation of implicit and explicit type conversion in C.
A short handwritten-style revision sheet for type conversion will be provided here.
Use the mind map for quick revision of implicit and explicit type conversion.