4 ms·
For the for loop example, is there some reason why clang doesn't output a warning like "Does 'i' really need to be signed? If so, explicitly make it a 'signed i
by mrpippy 11y ago
For the for loop example, is there some reason why clang doesn't output a warning like "Does 'i' really need to be signed? If so, explicitly make it a 'signed int'. Otherwise, change it to be unsigned"
- porges 11y agoThe point here is not particularly about signedness, it's that UB allows better optimizations to be performed. If overflow is defined to wrap around then it's potentially an infinite loop (take N == MAXVALUE). With overflow defined as UB you can say the loop executes exactly N times (because you're not allowed to write code that overflows). So UB is both bad and a source of power :)
- cowsandmilk 11y ago> The point here is not particularly about signedness But in the case of C, that is what it is about since unsigned integers have defined behavior, so you can only have UB and the optimizations when you use a signed integer.
- jeffreyrogers 11y agoYes, but more generally UB allows optimizations that wouldn't be allowed otherwise. The whole reason C has so many undefined behaviors is for the benefit of compiler writers.
- Joky 11y agoI believe it is not the original reason: most UB are about funky HW. For instance for the non-wrap signed int it can be explained because C does not assume you have 2-complement hardware.
- jcranmer 11y agoMore specifically, some early hardware would trap on signed overflow. A lot of undefined behavior in C actually comes from "some machine would cause a trap", and C predates the invention of precise trapping in out-of-order processors. The possibility of traps is generally the difference between undefined behavior or unspecified/implementation-defined behavior.
- GFK_of_xmaspast 11y agoIf N is unsigned, clang++ (and I think g++) will warn about signed/unsigned comparison, but sometimes you do want signed loop indices.
- tacos 11y agoMicrosoft's compiler has been ALL OVER THIS for 20 years. Nothing says "buggy port of Linux app to Windows" faster than "#pragma warning (disable: 4018)". Clang is catching up. GCC doesn't seem to care as much. Given all the bitching about undefined behavior you'd think they'd up the warnings. Compilers are programs too, y'know. We can define (and gasp, re-define) behavior.
- GFK_of_xmaspast 11y agoWell, in fairness and generality nothing says buggy like "disabled warnings". (and you know you're in trouble when you start looking at a new codebase and see a "-fpermissive" in there) Totally agree with more warnings being needed, I understand that exploiting UB is needed for optimization, but I don't buy the 'well we can't warn about every case, so we won't warn about any' reasoning.