liveBook · Manning

Signed integer arithmetic

As explained in Modern C, Third Edition

Signed arithmetic is arithmetic performed on values of signed integer types, with results subject to the rules for signed representations and overflow.

Signed integer arithmetic uses the same bit operations as unsigned arithmetic, while interpreting representations with a high-order 1 bit as negative under two’s complement. section 5.7.5

Signed overflow changes the rules

An unsigned counter eventually wraps from UINT_MAX to 0. A signed counter that overflows instead enters undefined behavior, allowing the compiler to assume the overflow never occurs and potentially transform the loop into an infinite loop. section 5.7.5

bool is_negative(unsigned a) {
  constexpr unsigned int_max = UINT_MAX/2;
  return a > int_max;
}
bool is_signed_less(unsigned a, unsigned b) {
  if (is_negative(a) != is_negative(b)) return a > b;
  else return a < b;
}

Compare unsigned values as signed values by detecting the sign bit and reversing the ordering when exactly one operand is negative. section 5.7.5

How Modern C, Third Edition covers it

How deep it goes
Explains two’s complement and compiler consequences of overflow, but defers broader undefined-behavior analysis.
Examples
Uses bitwise negation, sign detection, signed comparison, and contrasting unsigned and signed counter loops.
What it assumes
Assumes familiarity with unsigned arithmetic, bit operations, loops, and compiler optimization assumptions.
What you can do after
Diagnose why signed-overflow code cannot be reasoned about as wrapping arithmetic and may be optimized into an infinite loop.
How it connects
Connects signed arithmetic with unsigned integer types, two’s complement representation, undefined behavior, and compiler optimization.

Also explained in

Compare how 2 books explain signed integer arithmetic →

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.