Type conversion is an important concept in Semantic Analysis and Type Checking. It ensures that different data types can be used together safely in expressions.
Type conversion is the process of converting a value from one data type to another.
👉 It is used when different data types are involved in an expression or assignment.
There are two main types:
Implicit type conversion is performed automatically by the compiler when it converts one data type into another without programmer intervention.
👉 Also called type coercion.
Compiler automatically converts lower precision type → higher precision type.
char → int → float → double
int a = 10;
float b = 5.5;
float c = a + b;
a (int) → converted to float10.0 + 5.5float✔ No error occurs
char ch = 'A';
int x = ch;
'A' ASCII value → converted to intSometimes it may cause:
float x = 10.5;
int y = x; // decimal part lost
Explicit type conversion is when the programmer manually converts one data type into another using casting operators.
👉 Also called type casting.
(type) expression
float x = 10.5;
int y = (int)x;
10.5 → converted manually to 10int a = 10, b = 4;
float result = (float)a / b;
10 / 4 = 2.5 (correct result due to casting)(type)| Feature | Implicit Conversion | Explicit Conversion |
|---|---|---|
| Other name | Coercion | Type casting |
| Done by | Compiler | Programmer |
| Syntax | Automatic | (type) expression |
| Control | No control | Full control |
| Safety | Safer | Risk of data loss |
| Direction | Small → large | Large → small (usually) |
| Example | int → float | float → int |
Like automatically converting:
Like manually pouring:
✔ Implicit conversion is automatic ✔ Explicit conversion is manual ✔ Implicit is safer (widening conversion) ✔ Explicit may cause data loss (narrowing conversion) ✔ Used heavily in type checking phase of compiler
Type conversion is the process of converting one data type into another. Implicit conversion is performed automatically by the compiler when safe conversion is possible, while explicit conversion is performed manually by the programmer using type casting operators and may lead to data loss.
| Concept | Meaning | Example |
|---|---|---|
| Implicit conversion | Automatic conversion | int → float |
| Explicit conversion | Manual conversion | float → int |
| Coercion | Implicit conversion | a + b (auto type match) |
| Type casting | Explicit conversion | (int)x |
Open this section to load past papers