3 ms·
Hi everyone. I'm the author of the featured post; thanks for the interest. > If the code never calls the function with bad values, there's no UB Exactly. Even
by gergo_barany 9y ago
Hi everyone. I'm the author of the featured post; thanks for the interest.
> If the code never calls the function with bad values, there's no UB
Exactly. Even if a function might have undefined behavior for some input values, compilers are still required to compile the code correctly for the other input values (if any). And I would still expect them to optimize for those other input values.
Anyway, would everyone be happily convinced if I updated the example as follows?
#include <math.h>
#include <limits.h>
char fn1(float p1) {
if (isfinite(p1) && CHAR_MIN <= p1 && p1 <= CHAR_MAX) {
return (char) p1;
}
return 0;
}
I think that covers all that could possibly go wrong. And (unsurprisingly, to me at least) it still shows the same behavior with GCC of storing to the stack and reloading instead of zero-extending register-to-register.