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?
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?
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.
According to the C99 standard, the following operands are permissible for any relational operator:
In the former case, differing types will be converted according to the usual arithmetic conversions.
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;
}