Examples of Explicit Type Casting
Here are examples of explicit type casting in C, C++, Python, C#, and Java:
#include <iostream>
using namespace std;
int main()
{
double x = 10.5;
int y = (int)x; // Explicitly cast double to int
cout << "x: " << x << ", y: " << y << endl;
return 0;
}
#include <stdio.h>
int main()
{
double x = 10.5;
int y = (int)x; // Explicitly cast double to int
printf("x: %lf, y: %d\n", x, y);
return 0;
}
public class Main {
public static void main(String[] args)
{
double x = 10.5;
int y = (int)x; // Explicitly cast double to int
System.out.println("x: " + x + ", y: " + y);
}
}
using System;
class Program {
static void Main()
{
double x = 10.5;
int y = (int)x; // Explicitly cast double to int
Console.WriteLine("x: " + x + ", y: " + y);
}
}
x = 10.5
y = int(x) # Explicitly cast float to int
print("x:", x, ", y:", y)
Output
x: 10.5, y: 10
Explicit Type Casting
In programming, Data Types play a crucial role in defining the behavior and characteristics of variables. However, situations often arise where we need to convert data from one type to another. This process is known as Type Casting or Type Conversion. In this blog, we’ll understand Explicit Type Casting, exploring its applications, advantages, pitfalls, and best practices.
Table of Content
- What is Explicit Type Casting?
- When to Use Explicit Type Casting?
- Examples of Explicit Type Casting
- Explicit Type Casting of Incompatible Data Types
- Controlling precision and rounding behavior
- Advantages of Explicit Type Casting
- Disadvantages of Explicit Type Casting
- Explicit Type Casting Common Mistake