4 ms·
Well, first of all, Collatz isn't one of the millenium problems. Secondly, as others have already explained, endless loops are UB and optimized away, but, thir
by muldvarp 5y ago
Well, first of all, Collatz isn't one of the millenium problems.
Secondly, as others have already explained, endless loops are UB and optimized away, but, thirdly, even if they weren't, C++ integers are more like Z/nZ than Z and checking if Collatz holds in Z/nZ is rather trivial.
- stephencanon 5y ago> C++ integers are more like Z/nZ This is an widely-held misconception, but C++ signed integers are _nothing_ like Z/nZ. Unsigned integers are (except for division), and machine arithmetic often is, but in the C++ abstract machine, signed overflow is undefined behavior.
- vlovich123 5y agoThe snippet on Twitter uses unsigned.
- stephencanon 5y agoYes, it does.
- jasode 5y ago>, endless loops are UB and optimized away That soundbite also repeats/paraphrases what thread author Joe Groff said "LLVM considers infinite recursion to be UB," But... the key is infinite loops without side effects can be optimized away. Endless loops even without a provable termination (The Halting Problem) are not UB. But in this case, the value 'x' has a side effect of determining what bool of true/false value to return. That while() loop does not look like it's free of side effects.
- bidirectional 5y agoThe only return statement returns a hardcoded true.
- agent327 5y agoThere is no side effect. The loop only interacts with variable 'x', which is discarded after the function ends. Since it is not observed, there is no side effect. That leaves only the loop itself, which can run infinitely long (which would be UB, and the compiler is free to assume that won't happen), or it won't, in which case it will always return true. Thus, like them or not, the rules of C++ allow this particular outcome. I can't say I like this kind of optimisation. Sure, you can construct neat circus tricks with it like this, but other than that it seems pretty pointless for real-world software, and something that could easily turn a simple mistake into a debugging disaster.
- Denvercoder9 5y agoFor the purposes of the C++ standard, looping forever is not a side-effect. Only I/O calls, volatile accesses and atomic/synchronization operations are.
- gpderetta 5y ago"Side-effect" is a Word of Power that includes IO, volatile, atomics, and little else.