views:

217

answers:

3

Can someone explain how does less than op work in C?

In particular how it works when types of left hand side and right hand side operands are different?

Does it compare them based on type of the first one or the second one?

+9  A: 

C specifies standard conversions for different types. The rules are a bit complex, but basically the "smaller" type gets temporarily converted to the larger type, So if you compare an int with a char, the char will be converted to an int, for the purposes of the comparison only.

anon
The jargon for this is "the usual arithmetic conversions", which you can find in the index of *The C Programming Language* by Kernighan and Ritchie. The one surprise is that sometimes a signed operand is promoted to an unsigned type because the other operand is unsigned, so a large positive `unsigned int` might be considered less than a negative `int`.
Jason Orendorff
The other rule is that arithmetic (including comparisons) isn't ever done on types smaller than `int`, so if you compare a `char` with a `char`, they'll *both* be promoted to `int`.
caf
+1  A: 

According to the C99 standard, the following operands are permissible for any relational operator:

  • two operands with real arithmetic types
  • two pointers to objects of the same type

In the former case, differing types will be converted according to the usual arithmetic conversions.

ezod
A: 

Like Jason said in one of the comments, you have to be careful with unsigned types. For example the following code prints out BROKEN:

#include <stdio.h>

int main() {
  int a = -1;
  unsigned int b = 1 << 31;

  if (a < b) {
    fprintf(stderr, "CORRECT\n");
  } else {
    fprintf(stderr, "BROKEN\n");
  }

  return 0;
}
liwp