Type Casting - Like Transforming a Shape
Type casting means convert one data type into another data type.
Imagine you have a toy that can be a square or a circle. Type casting in C is like transforming that toy from a square to a circle or vice versa. It's a way to temporarily change the type of a variable.
Thre are mainly two types of type casting. that is Implicit & Explicit.
Implicit Type Casting (Automatic):
This happens automatically by the compiler. It's like when your friend has a square toy, and you need it to fit in a circle-shaped hole. The compiler figures out how to make it work without you explicitly telling it.
int myInt = 5;
float myFloat = myInt; // Implicit casting from int to float
Explicit Type Casting (Manual):
This is when you, the programmer, explicitly tell the compiler to change the type. It's like when your friend wants to make sure everyone knows they're now a circle, not a square.
syntex:
(newType) expression
example
float myFloat = 3.14;
int myInt = (int)myFloat; // Explicit casting from float to int
Explanation with example
Implicit Type Casting (Automatic):
example:
int myInt = 10;
float myFloat = myInt; // Implicit casting from int to float
printf("Integer: %d\n", myInt);
printf("Float: %.2f\n", myFloat);
output:
Integer: 10
Float: 10.00
Here, the integer myInt is implicitly cast to a float when assigned to myFloat. The compiler handles it automatically.
Explicit Type Casting (Manual):
example:
float myFloat = 3.14;
int myInt = (int)myFloat; // Explicit casting from float to int
printf("Float: %.2f\n", myFloat);
printf("Integer: %d\n", myInt);
output:
Float: 3.14
Integer: 3
Why Type Casting Matters:
Sometimes, you need to mix different types in an expression, and type casting helps you do that.
It ensures that your calculations are precise and that the types align correctly.
Remember, type casting is like transforming the shape of a variable temporarily, making sure it fits where you need it to!
0 Comments
If you have any doubts, Please let me know