user2341104
user2341104

Reputation:

Can I specify whether to cap or overflow integers in C/C++?

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

Upvotes: 2

Views: 1211

Answers (3)

Balog Pal
Balog Pal

Reputation: 17243

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.

Upvotes: 0

jamesdlin
jamesdlin

Reputation: 90174

"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.

Upvotes: 1

Clifford
Clifford

Reputation: 93566

"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.

Upvotes: 3

Related Questions