What happens if there is a mismatch of the signed / unsigned?

When the compiler finds a signature / unsigned mismatch, what action does it take? Is the number of signatures subscribed to unsigned or vice versa? and why?

+4
source share
3 answers

If the operand is integral and unsigned, then conversion to unsigned is performed. For instance:

-1 > (unsigned int)1 // as -1 will be converted to 2^nbits-1 

The conversion int-> unsigned int is: n> = 0 β†’ n; n <0 β†’ n (mod 2 ^ nbits), for example, -1 goes into 2 ^ nbits-1

Unsigned conversion int-> int: n <= INT_MAX β†’ n; n> INT_MAX -> implementation defined

If no destination type is specified, the resulting value is the smallest unsigned integer matching (modulo 2 ^ n, where n is the number of bits used to represent the unsigned type).

If the destination type is signed, the value does not change if it can be represented in the destination type (and the width of the bit field); otherwise, the value is determined by the implementation.

+3
source

I don't think C ++ deviates from the way C handles signed / unsigned conversions:

Conversion rules are more complex when unsigned operands are involved. The problem is that comparisons between signed and unsigned values ​​depend on the machine, because they depend on the sizes of the various integer types. (K & R)

One important factor to consider is whether one of the types is a long integer or not, because this will affect whole promotions. For example, if a long int compared to unsigned int , and a long int can represent all the values ​​of unsigned int , then unsigned int will be converted to long int . (Otherwise, both of them just convert to unsigned long int .)

In most cases, the compiler should convert signed integers to unsigned integers if it detects a mismatch.

+1
source

It may be compiler specific. If you look at the question " Should I turn off the C-compiler warning with a signed / unsigned compiler ? , you will see that in the case of" litb "the variable signed-var got" progressed "to an unsigned value.

In any case, there is no β€œright” way for the compiler to handle this situation when one variable reaches a certain value (that is, where is the most significant bit ). So, if you have such a warning, be sure to get rid of it;)

0
source

All Articles