compare char with hexadecimal



char c;
	
c = 0xf0;
if (c == 0xf0) {
  do something
}


The program not enter the if statement. It works when i use unsigned char instead of char. So I already have a Solution.

My question is: why does the compare operator not work with the negative hexadecimal numbers?
Warning	1	warning C4309: '=' : truncation of constant value

My compiler dont throw this warning...

But I understand now. Thanks
That might be half of the explanation. It doesn't matter whether 0xf0 in "c = 0xf0" gets truncated, or is considered a negative number. You could ask, why doesn't the same happen to the 0xf0 in "c==0xf0". Well, that's because numeric literals are considered integers. When you compare two basic types, the smaller one is converted to the bigger one, so char==int performs a int==int rather than a char==char. Therefore nothing happens to that 0xf0. If you instead wrote "c == char(0xf0)" it should work fine.
char can hold only a value up to 0x7f. unsigned char can hold 0xff. thats why it works with unsigned char
Maybe you could try

1
2
3
4
5
char c = '\xf0';

if (c == '\xf0') {
  do something
}


This is my preferred form, as it is setting a char with a char value.

char c = 0xf0;


Is setting a char to an int value;

(Visual Studio warns about the second form with:
warning C4309: 'initializing' : truncation of constant value
but not the first!)

Andy
Topic archived. No new replies allowed.