Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing signed integer overflows in C/C++

I want signed integers to overflow when they become too big. How do I achieve that without using the next biggest datatype (or when I am already at int128_t)?

For example using 8bit integers 19*12 is commonly 260, but I want the result 1 11 10 01 00 with the 9th bit cut off, thus -27.

like image 310
Henry B. Avatar asked Nov 21 '10 22:11

Henry B.


People also ask

What happens when a signed int overflows?

"Signed integer overflow" means that you tried to store a value that's outside the range of values that the type can represent, and the result of that operation is undefined (in this particular case, your program halts with an error).

Does C have integer overflow?

In C, unsigned integer overflow is defined to wrap around, while signed integer overflow causes undefined behavior.

How does integer overflow work in C?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).

What happens if unsigned int overflows?

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.


2 Answers

Signed overflow is undefined in C, and that's for real.

One solution follows:

signed_result = (unsigned int)one_argument + (unsigned int)other_argument;

The above solution involves implementation-defined behavior in the final conversion from unsigned to int but do not invoke undefined behavior. With most compilation platforms' implementation-defined choices, the result is exactly the two's complement result that you expect.

Finally, an optimizing compiler for one of the numerous platforms on which implementation-defined choices force the compiler to give you the behavior you expect will compile the above code to the obvious assembly instruction.

Alternately, if you are using gcc, then the options -fwrapv/-fno-strict-overflow may be exactly what you want. They provide an additional guarantee with respect to the standard that signed overflows wrap around. I'm not sure about the difference between the two.

like image 118
Pascal Cuoq Avatar answered Sep 21 '22 16:09

Pascal Cuoq


Signed integer overflow is undefined according to both C and C++ standards. There's no way to accomplish what you want without a specific platform in mind.

like image 35
Billy ONeal Avatar answered Sep 20 '22 16:09

Billy ONeal