2

Can I chose whether to cap or overflow integer values in C/C++? Or are those compiled dependent?

3 Answers3

3

"Capping" as you refer to it is known as "saturation". It is common for Digital Signal Processors (DSP) to support saturation in hardware, but most microprocessors naturally overflow and wrap-around. Processors supporting DSP extensions such as MMX for example also support saturation.

Language support for saturation is normally by compiler extensions, intrinsics and libraries. It would be possible in C++ perhaps to create a template class for saturating arithmetic types.

From my answer to this question:

ISO/IEC JTC1 SC22 WG14 N1169 (Programming languages - C - Extensions to support embedded processors) specifies a _Sat type qualifier for saturating data types. I have never tried to use it in any compiler, but it is included in the GCC 4.x documentation.

VC++ 2003 onward supports MMX intrinsics that allow saturating arithmetic.

Note that on a processor without hardware support for saturating arithmetic, there is likely to be a performance hit in using it.

Community
  • 1
  • 1
Clifford
  • 88,407
  • 13
  • 85
  • 165
  • 1
    Software implementations of saturating arithmetic also make for hilarious graphs when the right university professor assigns it to students as an exercise. http://blog.regehr.org/archives/392 – Pascal Cuoq May 26 '13 at 14:33
1

"Overflowing" unsigned integer types is well-defined behavior that's dictated by the C and C++ standards. (To nitpickers: I know that it's not technically defined as overflow, but that's not the definition that fits what most people are actually interested in.)

Overflowing signed integer types, on the other hand, is undefined behavior. Anything could happen.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • 1
    So, let me get that straight, integer overflow is well-defined as undefined behavior? I get it, but one has to appreciate the logical paradox... –  May 26 '13 at 10:24
  • 1
    @user2341104: Note the distinction between *unsigned* and *signed* integer types. It's well-defined for one, undefined for the other. – jamesdlin May 26 '13 at 10:30
  • 1
    @user2341104 - No, it is defined for unsigned, undefined for signed. The "nitpicker" bit simply refers to the inaccuracy and common misuse of the term *overflow*. If misuse of a word is common enough it often by *defacto* comes to mean what the users intend it to mean. – Clifford May 26 '13 at 10:32
0

As James already said it's signed integer overflow is undefined behavior. See here https://www.securecoding.cert.org/confluence/display/seccode/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow for some ideas how to deal with it.

Balog Pal
  • 16,195
  • 2
  • 23
  • 37