At what point in the loop does integer overflow become undefined behavior?

If you’re interested in a purely theoretical answer, the C++ standard allows undefined behaviour to “time travel”: [intro.execution]/5: A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input. However, if … Read more

Is signed integer overflow still undefined behavior in C++?

is still overflow of these types an undefined behavior? Yes. Per Paragraph 5/4 of the C++11 Standard (regarding any expression in general): If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. […] The fact that a … Read more

Efficient unsigned-to-signed cast avoiding implementation-defined behavior

Expanding on user71404’s answer: int f(unsigned x) { if (x <= INT_MAX) return static_cast<int>(x); if (x >= INT_MIN) return static_cast<int>(x – INT_MIN) + INT_MIN; throw x; // Or whatever else you like } If x >= INT_MIN (keep the promotion rules in mind, INT_MIN gets converted to unsigned), then x – INT_MIN <= INT_MAX, so … Read more

(A + B + C) ≠ (A + C + B​) and compiler reordering

If the optimiser does such a reordering it is still bound to the C specification, so such a reordering would become: uint64_t u64_z = (uint64_t)u32_x + (uint64_t)u32_y + u64_a; Rationale: We start with uint64_t u64_z = u32_x + u64_a + u32_y; Addition is performed left-to-right. The integer promotion rules state that in the first addition … Read more