1

As c++ newbie, I can't fully understand why the following code doesn't work (by "doesn't work" I mean, I don't see the output 255 but instead a "broken" character):

uint8_t num = 0xff;
std::cout << num << std::endl;

I guess, num is treated here somehow like a (non printable) character.

But I've found a code sample that solves my problem:

uint8_t num = 0xff;
std::cout << +num << std::endl;

At the moment, I have no idea what the + operator does in this case, and I really don't know how to google this question...

I would really appreciate it if someone could point me to right direction. Many thanks in advance!

Edit:

The first part of my question is duplicate of:

uint8_t can't be printed with cout

The answer to second part of my question (why the unary + operator helps in this case) can also be found there if you read through all answers and comments. The keyword is integer promotion

bmk
  • 1,548
  • 9
  • 17
  • 1
    The + operator promotes it to an integer, which is then printed as a number. – erenon Oct 19 '17 at 06:32
  • Edit your question to get rid of any sense of the duplicate material. Then it may be answered. – StoryTeller - Unslander Monica Oct 19 '17 at 06:44
  • Oh, and don't place "EDIT" in all caps. The post should be readable and self contained, without any ad-hoc versioning. The site will keep up of the edit history just fine on its own. – StoryTeller - Unslander Monica Oct 19 '17 at 06:46
  • Sry for that. Actually after reading through all the answers https://stackoverflow.com/questions/19562103/uint8-t-cant-be-printed-with-cout answered all my questions. Please close the question. – bmk Oct 19 '17 at 07:14
  • @erenon: thank you too, you've also answered the second part of my question correctly – bmk Oct 19 '17 at 07:18

0 Answers0