
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 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 view and download past papers
Click on Show Past Papers to load available exam papers.