我理解C语言在整数和浮点类型之间的隐式转换,但我对签名/无符号隐式类型转换有疑问.
例如,如果添加unsigned char和signed int,结果类型是什么?它会是unsigned int,signed int还是其他什么?
我没有看到C99 ANSI标准中有任何具体内容,所以任何帮助都表示赞赏.
解决方法
在C99中,参考是6.3.1.8“常用算术转换”.
Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result. For the specified operands,each operand is converted,without change of type domain,to a type whose corresponding real type is the common real type. Unless explicitly stated otherwise,the common real type is also the corresponding real type of the result,whose type domain is the type domain of the operands if they are the same, and complex otherwise. This pattern is called the usual arithmetic conversions:
- First,if the corresponding real type of either operand is
long double ,the other operand is converted,without change of type domain,to a type whose corresponding real type is long double .
- Otherwise,if the corresponding real type of either operand is
double ,to a type whose corresponding real type is double .
- Otherwise,if the corresponding real type of either operand is
float ,to a type whose corresponding real type is float . 51)
- Otherwise,the integer promotions are performed on both operands. Then the
following rules are applied to the promoted operands:
- If both operands have the same type,then no further conversion is needed.
- Otherwise,if both operands have signed integer types or both have unsigned
integer types,the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
- Otherwise,if the operand that has unsigned integer type has rank greater or
equal to the rank of the type of the other operand,then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
- Otherwise,if the type of the operand with signed integer type can represent
all of the values of the type of the operand with unsigned integer type,then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
- Otherwise,both operands are converted to the unsigned integer type
corresponding to the type of the operand with signed integer type.
添加执行通常的算术转换,因此,在添加unsigned char和signed int时,要么:
>首先将unsigned char提升为int,然后两个类型相同,因此结果的类型为int,或>(uncommon)int不能表示所有可能的unsigned char值.在这种情况下,unsigned char被提升为unsigned int,并且第三个子项应用:unsigned int具有与int相等的等级,因此int操作数被转换为unsigned int,结果的类型为unsigned int.
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|