Questions / Quant development, Numerics & testing

Signed overflow is not a portable wraparound rule

Applied, about 6 minutes. Question D037.

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?

  1. AYes; signed arithmetic follows the same modular rule as unsigned.
  2. BNo; signed overflow has undefined behavior in the language model.
  3. CNo; wraparound is guaranteed when optimizations are turned off.
  4. DYes; storing the result in the same signed type forces wraparound.

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.

  1. Distinguish the machine’s bit representation from the language semantics of the expression.
  2. Overflowing signed addition is not given portable wraparound behavior.
  3. 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.

More numerics & testing questions