ADVERTISEMENT
ADVERTISEMENT

Type Conversion in C with Examples

Type conversion, also known as type casting, refers to changing an expression of a given type into another type. In other words you can say that converting one data type into another is known as type casting or, type-conversioIn C, type conversion can be Explicit or Implicit.

 It is performed using a type cast operator, which is a set of parentheses that contain the desired type.

The syntax for a type cast operator is as follows:

(type) expression

Explicit Type Conversion

Explicit type casting is the process of explicitly converting an expression of one data type into another data type using a type cast operator. The syntax for a type cast operator is as follows:

int x = 10;
float y = (float) x;  // explicit type conversion from int to float

In this example, the value of x is converted from an int to a float using a type cast operator.

Here's another example of explicit type casting:  

char c = 'A';
int i = (int) c;  // i will be assigned the value 65


In this case, the value of c is a char and is explicitly converted to an int using a type cast operator. The ASCII value of the character 'A' is 65, so i will be assigned this value.

Implicit type conversion

Implicit type conversion, on the other hand, is performed automatically by the compiler when an expression of one type is used in a context that requires a different type. For example:

float x = 10.5;
int y = x;  // implicit type conversion from float to int

int x = 10;
char c = x;  // c will be assigned the value 

In this case, the value of x is an int and is implicitly converted to a char without using a type cast operator. The ASCII value of the character ' ' is 10, so c is assigned this value.

It's important to be aware of the potential loss of precision when using type casting, especially when converting from a larger type to a smaller type. Always be sure to carefully consider whether explicit or implicit type casting is appropriate for a given situation.


ADVERTISEMENT

ADVERTISEMENT