**Type Conversion** is the process of converting a variable from one data type to another. In C, this is essential when performing operations involving different types, such as adding an int to a float. Without proper conversion, you might lose precision or encounter unexpected results in your calculations.
Implicit conversion, also known as Automatic Type Conversion, is performed by the compiler without any intervention from the programmer. This usually happens when you assign a value of a smaller data type to a larger data type. This is also called "Type Promotion."
For example, if you add an int and a float, the compiler will automatically convert the int to a float before performing the addition to avoid losing decimal information.
Explicit conversion, or Type Casting, is performed manually by the programmer. You tell the compiler exactly which type you want the value to be changed into. This is done by placing the desired data type in parentheses (type) before the value.
Sometimes the compiler’s automatic conversion doesn't give you what you want. A classic example is integer division. In C, 5 / 2 results in 2 (the decimal part is chopped off). To get 2.5, you must cast one of the numbers to a float.
It is important to understand the direction of conversion to prevent data loss:
int to double). This is safe as no data is lost.float to int). This is risky because the fractional part will be deleted (truncated).| Operation | Example | Resulting Value |
|---|---|---|
| Float to Int | (int) 9.99 |
9 (Loss of .99) |
| Int to Float | (float) 5 |
5.000000 |
| Char to Int | (int) 'A' |
65 (ASCII Value) |
Imagine you are calculating the average of numbers. If the sum and count are integers, the average will be wrong unless you use type conversion.
When working with type conversion in C, keep these rules in mind to ensure AdSense-quality professional code:
long value into a short int, as it may cause "Overflow" and result in garbage values.