0

If we assign an out-of-range value to an object of unsigned type, the result is the remainder of the value modulo the number of values the target type can hold. This is natural. However, if we assign an out-of-range value to an object of signed type, the result is undefined. Why doesn't the C++ standard define an exactly result of this behavior, such as the unsigned case???

Shangchih Huang
  • 319
  • 3
  • 11
  • How would you define `signed` integer overflow? What is the result of `INT_MAX + 1`? – mch Mar 13 '17 at 09:58

1 Answers1

1

Because some processors generate a hardware exception on arithmetic overthrow. To define behaviour, the C++ code would have to insert a trap between almost every alu instruction, slowing the program to a crawl.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18
  • In C, the behavior of assigning an *existing* integer value to a signed type which is too small to hold it is defined as either storing an implementation-defined value or raising an implementation-defined signal. I don't know of any non-two's-complement systems that support a 64-bit unsigned integer type (as required by current standards for both C and C++), so I don't think avoiding traps would be a problem. On the other hand, for some applications trapping on overflow could be useful but allowing compiler writers to use their own judgment in deciding what forms of trap would be useful... – supercat Mar 13 '17 at 16:48
  • ...makes more sense than having the Standards Committee guess at such things. Unfortunately, while Undefined Behavior used to be interpreted as "Behave in whatever fashion would make an implementation most suitable for its intended purpose" [for the authors of the Standard to have *said* so would have patronizingly implied that they expected that compiler writers would otherwise implement behaviors unsuitable for their intended purposes] compiler writers seem to assume a compiler's suitability for any particular purpose should depend upon nothing more than conformance to the Standard. – supercat Mar 13 '17 at 16:55