A. Sarid - 9 months ago 50

C Question

I was searching around a little trying to find an answer to this, but I couldn't find a clear cut answer.

I saw this answer where he wrote as a side note:

The rules are different for unsigned types; the result of converting a

signed or unsigned integer to an unsigned type is well defined.

So what is the

When converting from

`unsigned long long`

`unsigned int`

Lets assume that

`sizeof(unsigned int)`

`4`

`sizeof(unsigned long long)`

`8`

Is there a different behavior when assigning without casting and when assigning with casting?

Answer

The standard says:

6.3.1.3 Signed and unsigned integers

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

2 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.^{49)}

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

Point 2 describes a modulo operation, which has the same effect than cutting off the MSBs in this case. (It has the same effect when the maximum value of the new type plus one is a power of the number base.)

There's no difference if you use casting.