For a lot of C compilers a char
is a signed 8-bit integer.
A signed 8-bit integer can only hold values from -128 to 127. They can not hold a value like 0x80, 0xE2, etc.
For something like if(c == 0xAC)
the compiler knows that the value in c
can't be higher than 127, and therefore knows that the condition must be false. For this reason, a compiler can optimise your code (by eliminating all code that can't be reached due to "must be false" conditions) down to getchar();printf("%c", 0x24);
.
To fix this use uint8_t
instead of char
. If you can't find a uint8_t
(e.g. you're stuck with an ancient dialect of C) then use an unsigned char
.
However..
It's possible that the input is actually coming from a file or something and not coming from the keyboard at all. For this reason you should handle EOF
properly. EOF
will not fit in a (signed or unsigned) char
and will not fit in a uint8_t
either. This means you should store the value returned by getchar()
in an int
, then compare with EOF
, then cast it to unsigned char
or uint8_t
with a type cast to compare it 0xAC.
Basically, it becomes a bit like this:
int c;
c = getch();
if(c == EOF) exit(0);
if( (uint8_t)c == 0xC2) {
...
}