[英]What would be the expression, true or false
uint8_t ui8 = 255;
ui8 == (int16_t)-1
As far as I understand the standard : 据我了解的标准 :
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.
否则,如果带符号整数类型的操作数的类型可以表示带无符号整数类型的操作数的所有值,则带无符号整数类型的操作数将转换为带符号整数类型的操作数的类型。
ui8
would be converted/promoted to int16_t and then it's arithmetic value would be -1
. ui8
将被转换/提升为int16_t,然后它的算术值为-1
。 Unfortunately the compiler I am using says I am not right. 不幸的是,我使用的编译器说我不正确。
Whenever a uint8_t
or any other small integer type is used as part of an expression, it gets integer promoted to type int
. 每当将
uint8_t
或任何其他小整数类型用作表达式的一部分时,都会将其提升为int
类型的int
。 The same goes for int16_t
, in case int
is larger than 16 bits. 如果
int
大于16位,则int16_t
也是如此。
So your code is guaranteed to be equal to: 因此,您的代码保证等于:
(int)255 == (int)-1
which is always false. 这总是错误的。
Because of integer promotions, both operands are already of the same type, so no balancing between operands takes place. 由于整数提升,两个操作数已经具有相同的类型,因此操作数之间不会发生平衡。
variable ui8
, with value 255
will be converted to type int
for the comparison, where it still has value 255
. 变量
ui8
值为255
将被转换为int
类型以进行比较,但该变量仍为255
。
Value (int16_t)-1
will also be converted to type int
, where it still has value -1
. 值
(int16_t)-1
也将转换为int
类型,但它仍具有值-1
。
255
compared against -1
is false
. 255
与-1
比较为false
。
ui8 would be converted/promoted to int16_t and then it's arithmetic value would be -1.
ui8将被转换/提升为int16_t,然后其算术值为-1。
Yes , type of ui8
will be converted/promoted .(As mentioned by Lundin Sir !! in comment ) Its because of integer promotion
thus ui8
will be promoted to type int16_t
in case int
is 16 bit
but if on your machine int
is larger than 16 bit
then both will be promoted to int
. 是的,
ui8
类型将被转换/提升。(正如Lundin Sir !!在评论中提到的)。由于integer promotion
因此如果int
为16 bit
但如果在您的机器上int
大于,则ui8
将被提升为int16_t
类型。然后16 bit
将两者都提升为int
。
And as per your quote from standards , it says about type not the values. 根据您对标准的引用,它说的是类型而不是值。 So
ui8
will retain its value ie 255
. 因此
ui8
将保留其值255
。
And thus - 因此 -
ui8==(int16_t)-1 // may be (int)u8==(int)-1 depends on size of int on you machine
results in false
. 结果为
false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.