How do signed integer overflow, unsigned modulo arithmetic, integer promotions, narrowing, and checked arithmetic differ in C++?
Show answer and explanation
If a signed integer result is not representable, the behavior is undefined; an optimizer may therefore assume that signed overflow never occurs. Unsigned arithmetic is reduced modulo one more than the maximum value, which is defined but can still be a logic or security bug. Before most arithmetic, integral promotions and the usual arithmetic conversions choose the operation type, so small integers and mixed signed/unsigned operands may not compute in the type suggested by their spelling. List initialization rejects many narrowing conversions at compile time, while ordinary casts and assignments can still lose range. Checked arithmetic must establish that the result is representable before performing an operation that could overflow, or use a suitable wider type, compiler checked intrinsic, or reviewed numeric library. Never perform signed overflow first and attempt to detect it afterward. Treat sizes, counts, multiplication, and allocation calculations as input-validation boundaries.
If a signed integer result is not representable, the behavior is undefined; an optimizer may therefore assume that signed overflow never occurs. Unsigned arithmetic is reduced modulo one more than the maximum value, which is defined but can still be a logic or security bug. Before most arithmetic, integral promotions and the usual arithmetic conversions choose the operation type, so small integers and mixed signed/unsigned operands may not compute in the type suggested by their spelling. List initialization rejects many narrowing conversions at compile time, while ordinary casts and assignments can still lose range. Checked arithmetic must establish that the result is representable before performing an operation that could overflow, or use a suitable wider type, compiler checked intrinsic, or reviewed numeric library. Never perform signed overflow first and attempt to detect it afterward. Treat sizes, counts, multiplication, and allocation calculations as input-validation boundaries.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.