1

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?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Timm
  • 45
  • 1
  • 6

3 Answers3

2

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.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • is it not int since int can represent the values of both the operands? – Koushik Shetty Nov 25 '13 at 11:44
  • Compiler can choose between `unsigned int` and `unsigned short` since both are able to represent two values, however the standard is more specific for `int`. – masoud Nov 25 '13 at 11:47
  • @MM. _IF_ the size of `int` is larger than the size of `short`. But on a typical 32 (or 64) bit machine, yes. They will both be converted to `int` before the comparison. – James Kanze Nov 25 '13 at 12:00
  • @JamesKanze: I was confused. Thanks for making it clear to me. – masoud Nov 25 '13 at 12:02
1

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

john
  • 85,011
  • 4
  • 57
  • 81
0

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

teroi
  • 1,087
  • 10
  • 19