Why is std::cout not printing the correct value for my int8_t number?

Grammin picture Grammin · Sep 28, 2011 · Viewed 17.1k times · Source

I have something like:

int8_t value;
value = -27;

std::cout << value << std::endl;

When I run my program I get a wrong random value of <E5> outputted to the screen, but when I run the program in gdb and use p value it prints out -27, which is the correct value. Does anyone have any ideas?

Answer

Cat Plus Plus picture Cat Plus Plus · Sep 28, 2011

Because int8_t is the same as signed char, and char is not treated as a number by the stream. Cast into e.g. int16_t

std::cout << static_cast<int16_t>(value) << std::endl;

and you'll get the correct result.