St.Antario
St.Antario

Reputation: 27435

Understanding integer sum in C

I'm trying to formally understand how additive operators work from the Standard's formal standpoint. There are 2 bullets:

4 If both operands have arithmetic type, the usual arithmetic conversions are performed on them.

5 The result of the binary + operator is the sum of the operands.

Considering the following piece of code

unsigned int m = UINT_MAX;
printf("%d\n", m + 1);

we have that UINT_MAX + 1 does not fit the width of unsigned int so to represent the result unsigned int is not enough. So I found a section describing unsigned integers conversions:

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.

The new type here is unsigned int, but the problem is what is the old type then? It cannot be unsigned int since the resulting value cannot be represented due to the width of unsigned int is too small.

Upvotes: 0

Views: 147

Answers (2)

4386427
4386427

Reputation: 44329

It cannot be unsigned int since the resulting value cannot be represented due to the width of unsigned int is too small.

That statement is not correct.

(Quotes below are from the draft standard N1570.)

The code is adding an unsigned int and a signed int.

Section 6.3.1.8 Usual arithmetic conversions describes what happens. The relevant part is:

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

and 6.3.1.1 Boolean, characters, and integers tells us

The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type, if any.

So these two sections tell that in case of unsigned-int + signed-int the signed int will be converted to unsigned int. So in your specific example "the old type" is indeed unsigned int.

With respect to the result of the operation Section 6.2.5 Types tells us:

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.

In other words, the result for your code is zero with type unsigned int.

So the relevant conversion is in 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.

Upvotes: 2

MSalters
MSalters

Reputation: 180020

The old types are unsigned int and int, UINT_MAX and 1 respectively.

The wording quoted describes the mathematical result, and math is not restricted to C types.

Upvotes: 2

Related Questions