unsigned int with signed long int (same width) - how is conversion done?

Discussion in 'C Programming' started by G Fernandes, Feb 16, 2005.

1. G FernandesGuest

Hello,

I have a question about using an unsigned int and a signed long int in
an expression (where UINT_MAX > LINT_MAX).

Based on the conversion rules, the unsigned int will be convered to
long int, but what if it can't fit? Is this undefined behaviour?

Any help will be appreciated.

[I guess the same thing can happen with unsigned long and signed long
long]

G Fernandes, Feb 16, 2005

2. Christian KandelerGuest

G Fernandes wrote:

> I have a question about using an unsigned int and a signed long int in
> an expression (where UINT_MAX > LINT_MAX).
>
> Based on the conversion rules, the unsigned int will be convered to
> long int

No, it won't. If signed long can't hold all possible values for unsigned
int, both operands are converted to unsigned long. This is part of the
"usual arithmetic conversions", which are explained in great detail in the
standard.

Christian

Christian Kandeler, Feb 16, 2005

3. Lawrence KirbyGuest

On Tue, 15 Feb 2005 21:25:25 -0800, G Fernandes wrote:

> Hello,
>
> I have a question about using an unsigned int and a signed long int in
> an expression (where UINT_MAX > LINT_MAX).
>
> Based on the conversion rules, the unsigned int will be convered to
> long int, but what if it can't fit? Is this undefined behaviour?

In that case both are converted to unsigned long.

> Any help will be appreciated.
>
> [I guess the same thing can happen with unsigned long and signed long
> long]

That's the normal case where the signed value is converted to the
unsigned type.

Any integer value can be converted to an unsigned type with a well defined
result. That may not preserve the value, and obviously won't if the
initial value is negative. When the value of an integer conversion can't
be represented in the new type the standard says:

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

So, for example, it follows that if you convert the value -1 to any
unsigned type the result is the maximum value that the unsigned type can
represent.

Lawrence

Lawrence

Lawrence Kirby, Feb 16, 2005