Type Conversion

Type Conversion

In C programming language, type conversion refers to the process of converting one data type to another. There are two types of type conversion: implicit and explicit.

Implicit type conversion, also known as type promotion, occurs automatically when the compiler converts one data type to another without any explicit instructions from the programmer. For example, when an int is added to a float, the int is automatically promoted to a float before the addition takes place.

Explicit type conversion, also known as type casting, occurs when the programmer explicitly instructs the compiler to convert one data type to another. This is done by placing the desired type in parentheses before the value or variable to be converted. For example, to convert an int to a float, you would write:

				
					int num = 10;
float num_float = (float) num;

				
			

Here are some common data type conversions in C:

  1. int to float or double: The int is automatically promoted to a float or double when used in a mathematical expression with a float or double.
  2. float or double to int: The float or double value is truncated (rounded down) to the nearest integer when converted to an int.
  3. char to int: The ASCII value of the char is returned when converted to an int.
  4. int to char: The int value is converted to its corresponding ASCII character when converted to a char.

It’s important to use type conversion carefully and to make sure that the converted value is within the range of the target data type, as type conversion can sometimes result in loss of precision or unexpected behavior.

Join To Get Our Newsletter
Spread the love