QP School

Full Version: Implicit and explicit type conversion in C
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Description:

The float data type is useful for representing real numbers with moderate precision. However, it's important to be cautious when comparing float values for equality due to the limited precision. In some cases, you may need to use double data type, which offers higher precision, when working with very small or very large real numbers.

Example:

int intValue = 10;
float floatValue = 2.5;

// Implicit type conversion (promotion)
float result1 = intValue + floatValue; // Result is 12.5

// Explicit type conversion (type casting)
int result2 = (int)(intValue + floatValue); // Result is 12

Explanation:

In this example, we have an int variable intValue with the value 10 and a float variable floatValue with the value 2.5.
In the first expression, intValue is implicitly converted to float during the addition with floatValue. This is called promotion, where the int is promoted to a float to ensure consistent types during the operation.
In the second expression, we use explicit type casting (type conversion) to convert the result of the addition back to an int. The (int) before the expression indicates the type casting operation.