Questions / Quant development, Numerics & testing
Signed overflow is not a portable wraparound rule
In C++, a signed integer addition exceeds the representable range of its type. Is two’s-complement wraparound a portable language guarantee for that expression?
Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.
Show the answer and worked solution
Answer: B. No; signed overflow has undefined behavior in the language model.
- Distinguish the machine’s bit representation from the language semantics of the expression.
- Overflowing signed addition is not given portable wraparound behavior.
- Use an appropriate checked operation, prove sufficient range, or choose unsigned arithmetic when modular behavior actually fits the contract.
Interview shortcut. Signed overflow is UB in C++.
Takeaway. Common hardware behavior is not a portable signed-overflow guarantee.
Why the other choices fail
- Yes; signed arithmetic follows the same modular rule as unsigned. Unsigned modular semantics do not apply to overflowing signed arithmetic.
- No; wraparound is guaranteed when optimizations are turned off. Optimization level does not change the language rules. Signed overflow is undefined behavior at every setting.
- Yes; storing the result in the same signed type forces wraparound. The receiving type does not define a result for an already-undefined overflowing expression.
In the app this has a follow-up where one thing about the setup changes. Try the follow-up.