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

G

G Fernandes

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]
 
C

Christian Kandeler

G said:
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
 
L

Lawrence Kirby

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top