Is conversion from unsigned to signed undefined?

1) Is a again converted to unsigned and compared with b ?

Yes. In the expression (a==b), the implicit type conversion called “balancing” takes place (the formal name is “the usual arithmetic conversions”). Balancing rules specify that if a signed and a unsigned operand of the same size and type are compared, the signed operand is converted to a unsigned.

2) Will b(ie unsigned ) be ever casted to signed value and compared automatically?

No, it will never be converted to signed in your example.

3) Is conversion from unsigned to signed undefined due to int overflow ?

This is what the standard says: (C11)

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.

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.

In other words, if the compiler can manage to do the conversion in 2) above, then the behavior is well-defined. If it cannot, then the result depends on the compiler implementation.

It is not undefined behavior.

Browse More Popular Posts

Leave a Comment