3 ms·
The example is comparing signed and unsigned chars. So 255 is casted to -1 in the comparsion. The compiler is not wrong for returning 1. Generally read left to
by anfilt 7y ago
The example is comparing signed and unsigned chars. So 255 is casted to -1 in the comparsion. The compiler is not wrong for returning 1. Generally read left to right. The first number is a signed char so the compiler may then try to convert any types to the right of the operation to a signed value as well.
If your comparing between types make your casts explicit.
- jjnoakes 7y agoPromotion rules are more complicated than just left to right. In this example both sides are promoted to int.
- deleted 7y ago[deleted]
- anfilt 7y agoI am quite aware of that keep mind I said generally. However, still the compiler is not wrong returning 1 in the example. Let me show the parts of standard as to why. So first the operation is a relation expression. Both signed Char and Unsigned Char of the arithmetic type. So we will follow usual arithmetic conversions. https://i.ibb.co/92bHJMj/1.png https://i.ibb.co/92bHJMj/1.png So the when converting integer types the following applies. Particularly, the section I have highlighted. Both signed and unsigned char are also the same rank. So the signed char is converted to unsigned char. However, we have a problem -1 can't be represented in unsigned so we need to look a bit further. https://i.ibb.co/jRhqd9H/2.png https://i.ibb.co/jRhqd9H/2.png If we look here we can see the 3 applies. As you can see implementation defined. https://i.ibb.co/8XrXt34/3.png https://i.ibb.co/8XrXt34/3.png However, if we promote to a signed int as you suggest happens; we still run into the same thing. https://i.ibb.co/RppGK5D/4.png https://i.ibb.co/RppGK5D/4.png
- jjnoakes 7y agoYou are close, but a little off. Your first citation is correct - we have to perform the usual arithmetic conversions. In your second citation, though, you missed the very first paragraph in your picture: > The integer promotions are performed on both operands, then the following rules apply: (emphasis is mine). Before you apply those rules you have to perform the "integer promotions"; they are defined in section 6.3.1.1 subsection 2 and they say, in part, that operands of rank smaller than int (which we have in this example) are converted to int first (which is what my original reply was pointing out). Once both operands are converted to int, no more "usual arithmetic conversions" are needed, so the resulting operation is done on two ints, and the result has to be 0. This is not implementation-defined. (By the way your last citation is for extended integer types, which we are not dealing with here - we are dealing with the basic integer types here).
- ncmncm 7y agoI hope I never depend on code written by anfilt. It is a forlorn hope: anfilt is legion.