What is typecasting? What are the types of typecasting? Explain with example.

28 Dec 2022 Balmiki Mandal 0 C Programming

Understanding Typecasting and Its Types with Examples

Typecasting, also known as type conversion, is the process of converting a value from one data type to another in programming. It is a crucial aspect of programming languages that allow different data types and is often used to handle different types of data in an operation or expression.

There are two types of typecasting:

  1. Implicit Typecasting:
  2. Explicit Typecasting:

Implicit Typecasting:

Implicit typecasting is done automatically by the compiler during the execution of a program. It is also known as type promotion. In this type of typecasting, the value of a lower data type is converted to the value of a higher data type. For example, when we add an integer to a float, the integer value is implicitly converted to a float value.

Example:

int num1 = 10;
float num2 = 20.5;

// Implicit typecasting
float sum = num1 + num2; // num1 is implicitly converted to float

Explicit Typecasting:

Explicit typecasting is done manually by the programmer using the cast operator. In this type of typecasting, the value of a higher data type is converted to the value of a lower data type. It is also known as typecasting by user.

Example:

float num1 = 20.5;
int num2;

// Explicit typecasting
num2 = (int) num1; // num1 is explicitly converted to int using (int) cast operator

In the above example, the float value of num1 is explicitly converted to an integer value using the (int) cast operator. It is important to note that explicit typecasting can result in data loss or truncation if the value of a higher data type is larger than the range of the lower data type.

Overall, typecasting is a useful tool in programming for handling different data types and performing operations on them. However, it should be used carefully to avoid any unexpected results or errors.

Related Shearch 


What is typecasting in c?

What are the types of typecasting?

When we do type casting in c?

When to Avoid Type Casting in C Programming

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.