This problem may also be resolved by utilizing an approach based on reflection. One may compare the type of the expression with a float and then with a double by using __builtin_types_compatible_p()
. This function determines whether two types are the same. For this purpose, __typeof__
can handily retrieve the type of the expression and pass it to the built-in function, as follows:
#include <stdio.h>
int main() {
if (__builtin_types_compatible_p(__typeof__(9 / 3 / 2 * 6 + 2 * 1.5), float)) {
puts("float");
} else if (__builtin_types_compatible_p(__typeof__(9 / 3 / 2 * 6 + 2 * 1.5), double)) {
puts("double");
}
return (0);
}
See demo.
When the types are the same, the function returns 1; see more here.
Note: __typeof__
does not return a string but a system type.
Instead of providing the entire mathematical expression to typeof, one may simply pass 1.5 since the question really turns on what data type represents this floating-point value.
See related information: Syntax and Sample Usage of _Generic in C11.