286

Unsigned integer overflow is well defined by both the C and C++ standards. For example, the C99 standard (§6.2.5/9) states

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.

However, both standards state that signed integer overflow is undefined behavior. Again, from the C99 standard (§3.4.3/1)

An example of undefined behavior is the behavior on integer overflow

Is there an historical or (even better!) a technical reason for this discrepancy?

9
  • 67
    Probably because there is more than one way of representing signed integers. Which way is not specified in the standard, at least not in C++. Commented Aug 12, 2013 at 20:06
  • Useful link: en.wikipedia.org/wiki/Signed_number_representations Commented Aug 12, 2013 at 20:07
  • 7
    What juanchopanza said makes sense. As I understand it, the original C standard in a large part codified existing practice. If all implementations at that time agreed on what unsigned "overflow" should do, that's a good reason for getting it standardized. They didn't agree on what signed overflow should do, so that did not get in the standard. Commented Aug 12, 2013 at 20:07
  • 2
    @DavidElliman Unsigned wraparound on addition is easily detectable (if (a + b < a)) too. Overflow on multiplication is hard for both signed and unsigned types. Commented Aug 12, 2013 at 20:10
  • 5
    @DavidElliman: It is not only an issue of whether you can detect it, but what the result is. In a sign + value implementation, MAX_INT+1 == -0, while on a two's complement it would be INT_MIN Commented Aug 12, 2013 at 20:11

9 Answers 9

218

The historical reason is that most C implementations (compilers) just used whatever overflow behaviour was easiest to implement with the integer representation it used. C implementations usually used the same representation used by the CPU - so the overflow behavior followed from the integer representation used by the CPU.

In practice, it is only the representations for signed values that may differ according to the implementation: one's complement, two's complement, sign-magnitude. For an unsigned type there is no reason for the standard to allow variation because there is only one obvious binary representation (the standard only allows binary representation).

Relevant quotes:

C99 6.2.6.1:3:

Values stored in unsigned bit-fields and objects of type unsigned char shall be represented using a pure binary notation.

C99 6.2.6.2:2:

If the sign bit is one, the value shall be modified in one of the following ways:

— the corresponding value with sign bit 0 is negated (sign and magnitude);

— the sign bit has the value −(2N) (two’s complement);

— the sign bit has the value −(2N − 1) (one’s complement).


Nowadays, all processors use two's complement representation, but signed arithmetic overflow remains undefined and compiler makers want it to remain undefined because they use this undefinedness to help with optimization. See for instance this blog post by Ian Lance Taylor or this complaint by Agner Fog, and the answers to his bug report.

Sign up to request clarification or add additional context in comments.

31 Comments

The important note here, though, is that there remain no architectures in the modern world using anything other than 2's complement signed arithmetic. That the language standards still allow for implementation on e.g. a PDP-1 is a pure historical artifact.
@AndyRoss but there are still systems (OS + compilers, admittedly with an old history) with one's complement and new releases as of 2013. An example: OS 2200.
@Andy Ross would you consider "no architectures ... using anything other than 2's complement ..." today includes the gamut of DSPs and embedded processors?
@AndyRoss: While there are “no” architectures using anything other than 2s complement (for some definition of “no”), there definitely are DSP architectures that use saturating arithmetic for signed integers.
Saturating signed arithmetic is definitely compliant with the standard. Of course the wrapping instructions must be used for unsigned arithmetic, but the compiler always has the information to know whether unsigned or signed arithmetic is being done, so it can certainly choose the instructions appropriately.
|
21

Aside from Pascal's good answer (which I'm sure is the main motivation), it is also possible that some processors cause an exception on signed integer overflow, which of course would cause problems if the compiler had to "arrange for another behaviour" (e.g. use extra instructions to check for potential overflow and calculate differently in that case).

It is also worth noting that "undefined behaviour" doesn't mean "doesn't work". It means that the implementation is allowed to do whatever it likes in that situation. This includes doing "the right thing" as well as "calling the police" or "crashing". Most compilers, when possible, will choose "do the right thing", assuming that is relatively easy to define (in this case, it is). However, if you are having overflows in the calculations, it is important to understand what that actually results in, and that the compiler MAY do something other than what you expect (and that this may very depending on compiler version, optimisation settings, etc).

16 Comments

Compilers do not want you to rely on them doing the right thing, though, and most of them will show you so as soon as you compile int f(int x) { return x+1>x; } with optimization. GCC and ICC do, with default options, optimize the above to return 1;.
For an example program that gives different results when faced with int overflow depending on optimization levels, see ideone.com/cki8nM I think this demonstrates that your answer gives bad advice.
I have amended that part a bit.
If a C were to provide a means of declaring a "wrapping signed two's complement" integer, no platform that can run C at all should have much trouble supporting it at least moderately efficiently. The extra overhead would be sufficient that code shouldn't use such a type when wrapping behavior isn't required, but most operations on two's complement integers are identical to those on an unsigned integers, except for comparisons and promotions.
Negative values need to exist and "work" for the compiler to work correctly, It is of course entirely possible to work around the lack of signed values within a processor, and use unsigned values, either as ones complement or twos complement, whichever makes most sense based on what the instruction set is. It would typically be significantly slower to do this than having hardware support for it, but it's no different from processors that doesn't support floating point in hardware, or similar - it just adds a lot of extra code.
|
14

First of all, please note that C11 3.4.3, like all examples and foot notes, is not normative text and therefore not relevant to cite!

The relevant text that states that overflow of integers and floats is undefined behavior is this:

C11 6.5/5

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

A clarification regarding the behavior of unsigned integer types specifically can be found here:

C11 6.2.5/9

The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the representation of the same value in each type is the same. 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.

This makes unsigned integer types a special case.

Also note that there is an exception if any type is converted to a signed type and the old value can no longer be represented. The behavior is then merely implementation-defined, although a signal may be raised.

C11 6.3.1.3

6.3.1.3 Signed and unsigned integers

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

Comments

9

In addition to the other issues mentioned, having unsigned math wrap makes the unsigned integer types behave as abstract algebraic groups (meaning that, among other things, for any pair of values X and Y, there will exist some other value Z such that X+Z will, if properly cast, equal Y and Y-Z will, if properly cast, equal X). If unsigned values were merely storage-location types and not intermediate-expression types (e.g. if there were no unsigned equivalent of the largest integer type, and arithmetic operations on unsigned types behaved as though they were first converted them to larger signed types, then there wouldn't be as much need for defined wrapping behavior, but it's difficult to do calculations in a type which doesn't have e.g. an additive inverse.

This helps in situations where wrap-around behavior is actually useful - for example with TCP sequence numbers or certain algorithms, such as hash calculation. It may also help in situations where it's necessary to detect overflow, since performing calculations and checking whether they overflowed is often easier than checking in advance whether they would overflow, especially if the calculations involve the largest available integer type.

7 Comments

I don't quite follow - why does it help to have an additive inverse? I can't really think of any situation where the overflow behaviour is actually useful...
@sleske: Using decimal for human-readability, if an energy meter reads 0003 and the previous reading was 9995, does that mean that -9992 units of energy were used, or that 0008 units of energy were used? Having 0003-9995 yield 0008 makes it easy to calculate the latter result. Having it yield -9992 would make it a little more awkward. Not being able to have it do either, however, would make it necessary to compare 0003 to 9995, notice that it's less, do the reverse subtraction, subtract that result from 9999, and add 1.
@sleske: It's also very useful for both humans and compilers to be able to apply the associative, distributive, and commutative laws of arithmetic to rewrite expressions and simplify them; for example, if the expression a+b-c is computed within a loop, but b and c are constant within that loop, it may be helpful to move computation of (b-c) outside the loop, but doing that would require among other things that (b-c) yield a value which, when added to a, will yield a+b-c, which in turn requires that c have an additive inverse.
:Thanks for the explanations. If I understand it correctly, your examples all assume that you actually want to handle the overflow. In most cases I have encountered, the overflow is undesirable, and you want to prevent it, because the result of a calculation with overflow is not useful. For example, for the energy meter you probably want to use a type such that overflow never occurs.
...such that (a+b)-c equals a+(b-c) whether or not the arithmetic value of b-c is representable within the type, the substitution will be valid regardless of the possible range of values for (b-c).
|
4

Perhaps another reason for why unsigned arithmetic is defined is because unsigned numbers form integers modulo 2^n, where n is the width of the unsigned number. Unsigned numbers are simply integers represented using binary digits instead of decimal digits. Performing the standard operations in a modulus system is well understood.

The OP's quote refers to this fact, but also highlights the fact that there is only one, unambiguous, logical way to represent unsigned integers in binary. By contrast, Signed numbers are most often represented using two's complement but other choices are possible as described in the standard (section 6.2.6.2).

Two's complement representation allows certain operations to make more sense in binary format. E.g., incrementing negative numbers is the same that for positive numbers (expect under overflow conditions). Some operations at the machine level can be the same for signed and unsigned numbers. However, when interpreting the result of those operations, some cases don't make sense - positive and negative overflow. Furthermore, the overflow results differ depending on the underlying signed representation.

5 Comments

For a structure to be a field, every element of the structure other than the additive identity must have a multiplicative inverse. A structure of integers congruent mod N will be a field only when N is one or prime [a degnerate field when N==1]. Is there anything you feel I missed in my answer?
You are right. I got confused by the prime power moduli. Original response edited.
Extra confusing here is that there is a field of order 2^n, it is just not ring-isomorphic to the integers modulo 2^n.
And, 2^31-1 is a Mersenne Prime (but 2^63-1 is not prime). Thus, my original idea was ruined. Also, integer sizes were different back in the day. So, my idea was revisionist at best.
The fact that unsigned integers form a ring (not a field), taking the low-order portion also yields a ring, and performing operations on the whole value and then truncating will behave equivalent to performing the operations on just the lower portion, were IMHO almost certainly considerations.
2

C++ just picks up this behaviour from C.

I believe that with C that a disconnect has developed between it's users and it's implementers. C was designed as a more portable alternative to assembler and originally did not have a standard as such, just a book describing the language. In early C low level platform specific hacks were common and accepted practice. Many real-world C programmers still think of C this way.

When a standard was introduced, it's goal was largely to standardise existing practice. Some things were left undefined or implementation defined. I'm not convinced that much attention was paid to which stuff was undefined and which stuff was implementation defined.

At the time when C was standardised, twos complement was the most common approach, but other approaches were around, so C couldn't outright require twos complement.

If you read the rationale for standard C at https://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf where they discuss the choice of promotion semantics they decided that the "value preserving" semantics were safer, however they made this decision based on the assumption that most implementations used twos complement and handled wraparound quietly in the obvious manner.

Compiler vendors at some point however started treating signed overflow as an optimisation opportunity. This has turned signed overflow into a major footgun. Unless you carefully check every arithmetic operation to make sure it can't overflow you can end up triggering undefined behaviour.

Once undefined behaviour is triggered, "anything can happen". What that means in practice is that the value a variable actually contains may be outside the range of values the compiler assumes it can contain. That in turn can render bounds checking ineffective.

Comments

2

This is an old question, but there aren't many examples of the possible UB here to go with the reasoning. Here is one:

#include <limits.h>
#include <stdio.h>

int main(void) {
    int num = INT_MAX;
    if (num > 0)
        printf("%d > 0\n", num);
    if (num + 1 > 0)
        printf("%d > 0\n", num + 1);
    return 0;
}

With x86 GCC (13.2), both lines will print. With x86 Clang (17.0.1), only the first line will print.

Here is a link to try for yourself: https://godbolt.org/z/Gszd55bjs

What can happen here is that compilers are more or less allowed to assume that signed integers are infinite. So if a > x, then a + 1 is also > x - which is true for math, but not for fixed-size wrapping representations. This can be used for optimization, but the example here has the same results at -O0 as -O3

Moving the inner logic to a different file separate from the num definition (making it opaque) gets both compilers print both lines, which is something that could be pretty surprising when refactoring.

1 Comment

Did you know you can use gcc's -fwrapv option to specify that your machine uses twos-complement signed integers? If you do that, then it will correctly show INT_MAX+1 < INT_MAX no matter what optimization level is selected. godbolt.org/z/1ffzEvoeq
1

The most technical reason of all, is simply that trying to capture overflow in an unsigned integer requires more moving parts from you (exception handling) and the processor (exception throwing).

C and C++ won't make you pay for that unless you ask for it by using a signed integer. This isn't a hard-fast rule, as you'll see near the end, but just how they proceed for unsigned integers. In my opinion, this makes signed integers the odd-one out, not unsigned, but it's fine they offer this fundamental difference as the programmer can still perform well-defined signed operations with overflow. But to do so, you must cast for it.

Because:

  • unsigned integers have well defined overflow and underflow
  • casts from signed -> unsigned int are well defined, [uint's name]_MAX - 1 is conceptually added to negative values, to map them to the extended positive number range
  • casts from unsigned -> signed int are well defined, [uint's name]_MAX - 1 is conceptually deducted from positive values beyond the signed type's max, to map them to negative numbers)

You can always perform arithmetic operations with well-defined overflow and underflow behavior, where signed integers are your starting point, albeit in a round-about way, by casting to unsigned integer first then back once finished.

int32_t x = 10;
int32_t y = -50;  

// writes -60 into z, this is well defined
int32_t z = int32_t(uint32_t(y) - uint32_t(x));

Casts between signed and unsigned integer types of the same width are free, if the CPU is using 2's compliment (nearly all do). If for some reason the platform you're targeting doesn't use 2's Compliment for signed integers, you will pay a small conversion price when casting between uint32 and int32.

But be wary when using bit widths smaller than int

usually if you are relying on unsigned overflow, you are using a smaller word width, 8bit or 16bit. These will promote to signed int at the drop of a hat (C has absolutely insane implicit integer conversion rules, this is one of C's biggest hidden gotcha's), consider:

unsigned char a = 0;  
unsigned char b = 1;
printf("%i", a - b);  // outputs -1, not 255 as you'd expect

To avoid this, you should always cast to the type you want when you are relying on that type's width, even in the middle of an operation where you think it's unnecessary. This will cast the temporary and get you the signedness AND truncate the value so you get what you expected. It's almost always free to cast, and in fact, your compiler might thank you for doing so as it can then optimize on your intentions more aggressively.

unsigned char a = 0;  
unsigned char b = 1;
printf("%i", (unsigned char)(a - b));  // cast turns -1 to 255, outputs 255

3 Comments

"trying to capture overflow in an unsigned integer requires more moving parts" You mean signed?
"casts from unsigned -> signed int are well defined": This isn't correct; converting from unsigned to signed yields an implementation-defined result if the result can't be represented in the signed type. (Or an implementation-defined signal is raised.) Most implementations do wrap as you describe, but it's not guaranteed by the standard. C17 6.3.1.3p3
@NateEldredge: Yeah, in theory an implementation could do something wonky, but since implementation defined behaviors are required to uphold laws of time and causality, they're too boring to justify the effort required for wacky treatments.
-1

Building on the answers about using numbers as a ring mod 2^32, some hashing and checksum algorithms are built to be performed modulo a word size. For example, for a CRC code, common implementations choose a polynomial so that they can be computed very quickly using an unsigned 16-bit integer (Bluetooth, USB), 32-bit integer (Ethernet, GZIP, MPEG-2, Adler-32), 64-bit integer, etc. In these cases, the math operates on a polynomial over the finite field with 2 elements, which isn't important for this answer aside from just saying it maps directly to a binary integer and overflow is completely intended. Also, MD5 and SHA-1 are designed to use unsigned 32-bit ints with wrapping.

In my opinion, it's much safer to explicitly say when you want this overflow behavior. But getting the compiler to not warn about all the false positives without manually annotating every math operation is difficult. Linus Torvalds ranted last year against a proposal for the Linux kernel for C operator overloading by handling overflows with handlers:

I'm still entirely unconvinced.

The thing is, wrap-around is not only well-defined, it's common, and EXPECTED.

Example:

static inline u32 __hash_32_generic(u32 val) { return val * GOLDEN_RATIO_32; }

and dammit, I absolutely DO NOT THINK we should annotate this as some kind of "special multiply".

I have no idea how many of these exist. But I am 100% convinced that making humans annotate this and making the source code worse is absolutely the wrong approach.

Basically, unsigned arithmetic is well-defined as wrapping around, and it is so for a good reason.

So I'm going to have a HARD REQUIREMENT that any compiler complaints need to be really really sane. They need to detect when people do things like this on purpose, and they need to SHUT THE ^&% UP about the fact that wrap-around happens.

Any tool that is so stupid as to complain about wrap-around in the above is a BROKEN TOOL THAT NEEDS TO BE IGNORED.

Really. This is non-negotiable.

This is similar to the whole

    unsigned int a, b;

    if (a+b < a) ..

kind of pattern: a tool that complains about wrap-around in the above is absolutely broken sh*t and needs to be ignored.

So I think you need to limit your wrap-around complaints, and really think about how to limit them. If you go "wrap-around is wrong" as some kind of general; rule, I'm going to ignore you, and I'm going to tell people to ignore you, and refuse any idiotic patches that are the result of such idiotic rules.

Put another way the absolute first and fundamental thing you should look at is to make sure tools don't complain about sane behavior.

Until you have done that, and taken this seriously, this discussion is not going to ever result in anything productive.

Any kind of mindless "this can wrap around" is inexcusable.

And later:

It needs to be smarter than that. And yes, that means exactly taking into account how the result of the possible wrap-around is actually used.

If it's used as a size or as an array index, it might be a problem. But if it's used for masking and then a masked version is used for an index, it clearly is NOT a problem.

IOW, exactly the same as "a+b < a". Yes, "a+b" might wrap around, but if the use is to then compare it with one of the addends, then clearly such a wrap-around is fine.

A tool that doesn't look at how the result is used, and just blindly says "wrap-around error" is a tool that I think is actively detrimental.

And no, the answer is ABSOLUTELY NOT to add cognitive load on kernel developers by adding yet more random helper types and/or functions.

We already expect a lot of kernel developers. We should not add on to that burden because of your pet project.

Put another way: I'm putting the onus on YOU to make sure your pet project is the "Yogi Bear" of pet projects - smarter than the average bear.

As long as you are approaching this from a "this puts the onus on others", YOU are the problem.

Be the solution, not the problem.

          Linus

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.