MiddleDebuggingOccasionalNot answered yet
Why can this sum-of-squares loop be undefined?
a[i] can be up to ~50000 and sum is an int; for large n the total is wrong.
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += a[i] * a[i]; // a[i] up to ~50000
}
Find and fix the bug.
int arithmetic overflows for large squares, and signed overflow is undefined behavior (not wraparound), so a[i] * a[i] and the accumulating int sum can both overflow silently. Fix: use a wider type — long long sum and static_cast<long long>(a[i]) * a[i].
- ✗Believing signed overflow wraps around like unsigned instead of being UB
- ✗Assuming the multiplication promotes to double automatically
- ✗Blaming the loop index instead of the accumulator width
- →Why is signed integer overflow undefined behavior while unsigned wraps?
- →Why must you cast
a[i]tolong longbefore the multiplication, not after?