1

I'm trying to redirect a signed char to cout. It works fine under Windows/VS2019 thanks to How to output a character as an integer through cout?.

However, under Android, compiled with CLang, it does not behave as expected.

Here is the code:

char c = -1;
std::cout << "c signed is " << signed(c) << std::endl;
std::cout << "+c is " << +c << std::endl;

Under Windows, I get expected output:

c signed is -1
+c is -1

Under Android, I get expected output:

c signed is 255
+c is 255

What portable code would help displaying "-1" on all platform?

jpo38
  • 20,821
  • 10
  • 70
  • 151
  • 2
    It's implementation defined if `char` is signed or unsigned. On your computer it seems to be signed, while on Android it seems to be unsigned. If you want an explicit signed 8-bit integer then use `int8_t`. – Some programmer dude Dec 06 '21 at 11:20
  • Thanks, I'll try that and let you know – jpo38 Dec 06 '21 at 11:30
  • Refer to [Is char signed or unsigned by default?](https://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default) – Sander De Dycker Dec 06 '21 at 11:30
  • Note that `signed()` casts to `signed int`, not to `signed char`. `signed int` can hold both `255` and `-1`, so you will always see the value that is really stored in `char`. Try `static_cast(c)` to always see `-1`. – Yksisarvinen Dec 06 '21 at 11:42

1 Answers1

0

As commented by Yksisarvinen, Some programmer dude and Sander De Dycker, the problem does not come from the way c is redirected to the stream, but more from c's type itself. Using char should be avoided if you expect the variable to be signed, because char is not necessarily signed.

The problem is fixed by using int8_t or signed char instead of char.

jpo38
  • 20,821
  • 10
  • 70
  • 151