4 ms·
As the compiler assumes you wont produce such values, wouldnt it also optimise those range checks away?
by orangepanda 5y ago
As the compiler assumes you wont produce such values, wouldnt it also optimise those range checks away?
- nly 5y agoHe means simple stuff like ensuring a function like float unit_price (float volume, int count) { return volume / count; } is only called where count > 0
- colejohnson66 5y agoBut couldn’t the compiler optimize out the check because you’re guaranteeing to never divide by 0, so logically count would never be 0. Akin to undefined behavior almost.
- throwawaylinux 5y agoThis test can not be optimized to always true: if (count > 0) total += unit_price(volume, count); Are you confusing it with the opposite scenario: total += unit_price(volume, count); if (count == 0) printf("oops\n"); That test might be optimized out because divide by zero is undefined behavior.
- colejohnson66 5y agoI probably am confusing them. I don’t program in C or C++, so I’m not aware of all the “gotchas”, and can easily confuse them (as shown here). Not to mention that compilers have been getting more aggressive in optimizing undefined behavior.
- adrian_b 5y agoWhat the compiler assumes depends on the compilation options. Unfortunately most compilers have too permissive default options. C and C++ programs should always be compiled, at least during development, with strict options, e.g.: -fsanitize=undefined -fsanitize-undefined-trap-on-error or equivalent options, which eliminate all the horror stories with unexpected behavior caused by integer divide-by-zero or overflow, pointer overflow, out-of-bounds access and many others. Because unlike integer operations the FP operations are standardized, there is no need for compiler options, the behavior for exceptions can be controlled from the program with the functions defined in <fenv.h> in C or <cfenv> in C++.
- jcelerier 5y agoAt least GCC is I believe fairly buggy in that regard since isnan is optimised out, thus you cannot check if say an incoming value read from the network is a NaN. There's some lengthy discussion about it on the big tracker iirc..
- jcelerier 5y agoI was misremembering, was thinking about this recent convo on LLVM mailinglist: https://lists.llvm.org/pipermail/llvm-dev/2021-September/152530.html https://lists.llvm.org/pipermail/llvm-dev/2021-September/152...
- usefulcat 5y agoI don't think you are misremembering; -ffast-math causes __builtin_isnan and __builtin_isinf to unconditionally return zero, for both gcc and clang: https://godbolt.org/z/1qjxvW3KK https://godbolt.org/z/1qjxvW3KK I found this out the hard way several years ago and still have my own implementations of these functions laying about in case I want to use -ffast-math.