Define division by zero as infinity
Floating point division by zero is undefined by the C standard.
(IEEE754 - common but by no means ubiquitous - defines a / 0.0
to be +INF
if a
is positive, -INF
if a
is negative and NaN
if a
is also zero).
Your best bet is to define a function that models the division operator, and implement your behaviour there.
If you require this behaviour, use floating point numbers, which can represent infinity, and provide the desired behaviour. Note that technically this is undefined behaviour but in practice most compilers (all mainstream compilers for standard architectures) implement IEEE 754 semantics, e.g. GCC.
int main() {
float f = 42;
float g = f / 0.0f;
printf("%f\n", g);
}
Output:
inf
This is behaviour that can be relied on since it’s clearly documented by the compilers. However, when writing portable code make sure that you test these assumptions inside your code (e.g. by testing whether the preprocessor macro __STDC_IEC_559__
, as well as compiler-specific macros are defined).
If, for some reason, you need this behaviour for integer values, the only recourse is to make your own type. Something like this:
typedef struct {
int value;
bool is_inf;
bool is_nan;
} ext_int;
ext_int make_ext_int(int i) {
return (ext_int) {i, false, false};
}
ext_int make_nan() {
return (ext_int) {0, false, true};
}
ext_int make_inf(int sign) {
return (ext_int) {(sign > 0) - (sign < 0), true, false};
}
ext_int ext_div(ext_int a, ext_int b) {
if (a.is_nan || b.is_nan) {
return make_nan();
}
if (b.value == 0) {
return make_inf(a.value);
}
// TODO: insert other cases.
return (ext_int) {a.value / b.value, false, false};
}
… in a real implementation you’d pack the different flags rather than having a separate bool
for each, of course.