Type conversion in C refers to the process of converting one data type to another. In C, this can happen in two ways:
Implicit type conversion is automatically handled by the C compiler when it converts smaller data types to larger ones. This occurs when a smaller data type is assigned to a larger data type, and no special syntax is required for the conversion.
int a = 10; float b = a; // Implicit conversion from int to float printf("%f", b); // Output: 10.000000
Explicit type conversion, also known as type casting, allows the programmer to manually convert one data type to another using a cast operator. This type of conversion is necessary when you need to convert a larger data type to a smaller one or between incompatible types.
float a = 5.67; int b = (int) a; // Explicit conversion from float to int printf("%d", b); // Output: 5
Here are some examples of both implicit and explicit type conversions:
// Implicit type conversion char a = 'A'; // a = 65 (ASCII value) int b = a; // Implicit conversion from char to int double c = b; // Implicit conversion from int to double // Explicit type conversion double x = 7.89; int y = (int) x; // Explicit conversion from double to int printf("%d", y); // Output: 7
In some cases, type conversion between incompatible types can lead to errors or undefined behavior. Always ensure that the conversion makes sense and does not result in data loss or overflow.
// Invalid conversion char a = 'A'; int b = (int) "Hello"; // Error: cannot cast a string to an integer printf("%d", b);
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!