Type Conversion in C

In C programming, type conversion (also known as type casting) is the process of converting a value of one data type to another. This can be necessary in situations where a function expects a certain type of data, or when performing arithmetic or comparison operations involving different data types.

There are two main types of type conversion in C:

  1. Implicit type conversion
  2. Explicit type conversion

1. Implicit type conversion (also known as “type promotion”) – this occurs automatically when the compiler needs to perform an operation on two values of different data types. The compiler will convert one or both of the values to a “higher” data type in order to perform the operation.

For example, if you try to add an integer and a floating-point value, the compiler will automatically convert the integer to a floating-point value before performing the addition:

int x = 10;
float y = 3.14;
float sum = x + y; // x is implicitly converted to a float before the addition is performed

2. Explicit type conversion (also known as “type casting”) – this involves manually converting a value from one data type to another using a type cast operator. The type cast operator is a unary operator that takes the form of a set of parentheses containing the target data type, followed by the value to be converted.

For example, to explicitly convert a floating-point value to an integer, you can use the following code:

float x = 3.14;
int y = (int)x; // x is explicitly cast to an int

Note that when performing explicit type conversion, the value being converted may lose precision or information.

For example, if you convert a floating-point value to an integer, any fractional part of the value will be truncated.