compare 8bit value against 16bit value

限于喜欢 提交于 2019-12-12 23:23:07

问题


I was wondering what happens when an 8bit value is compared against a 16bit value.

I'll try to explain the problem by a code example:

bool result;
unsigned char a_8bit = 0xcd;
unsigned short b_16bit = 0xabcd;
result = a_8bit < b_16bit;

Possible results can be:

  • a_8bit is casted to unsigned short implicitly and compared to b_16bit as a 16bit value. Result is true
  • b_16bit is casted to unsigned char implicitly and compared to a_8bit as an 8bit value. Result is false

Does anybody has a clue what the compiler will do with this piece of code? Sure, i can try it out, but are there different interpretations by different compilers of this code?


回答1:


1 A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int. [§ 4.5]

So, compiler can promote both of them to unsigned int and then do the comparison.




回答2:


The first, although to be precise, both are converted to unsigned and then compared.




回答3:


Normal integer promotion rules apply, see for example: http://www.idryman.org/blog/2012/11/21/integer-promotion/



来源:https://stackoverflow.com/questions/20192064/compare-8bit-value-against-16bit-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!