简体   繁体   English

表达式是正确的还是错误的

[英]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因此如果int16 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM