How to convert between types
Observe arithmetic conversions
When an integer and a floating value are combined, the integer is converted. Integer division happens before assignment, so use a floating operand when needed.
int total = 7;
int count = 2;
double average = (double) total / count;
Expect narrowing to lose data
Converting a floating value to an integer discards its fraction. Converting to a type that cannot represent the value may produce an implementation-defined or wrapped result.
double measurement = 12.9;
int whole = (int) measurement; // 12
Check before converting
Validate the source against the destination range before a narrowing conversion. Include limits.h for integer limits.
if (value >= INT_MIN && value <= INT_MAX) {
int safe = (int) value;
printf("%d\n", safe);
}
Do not cast away warnings
A cast cannot make an invalid pointer, out-of-range value, or discarded qualifier safe. Fix the types or validate the data instead of hiding a diagnostic.