0

In the following code, it appears that std::cout does not print the variable of type uint8_t properly.

int main() {
    uint8_t var = 16;
    std::cout << "value: " << var << std::endl;
}

output:

value: 

I don't have problem with similar uintX_t types.

I know I'm missing something here, but I can't figure what it is.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
narengi
  • 1,345
  • 3
  • 17
  • 38

1 Answers1

1

uint8_t maps to unsigned char on most systems. As the result, the override that interprets 16 as a non-printable character gets invoked. Add a cast to int to see the numeric value:

std::cout << "value: " << (int)var << std::endl;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I was suspecting that this implicit char casting is going on. But why? doesn't the type name, uint8_t, suggest that it should remain in its int form? – narengi Jun 16 '15 at 00:05
  • 1
    @narengi `uint8_t` is only a `typedef`, not a built-in primitive type. Because of that the compiler has no way to distinguish an override on the actual primitive type and an override on a `typedef`-ed type: it's the same function to the compiler. – Sergey Kalinichenko Jun 16 '15 at 00:07
  • Thank you for the clarification. So if I understood you correctly, it's a typedef on `char`, right? – narengi Jun 16 '15 at 00:09
  • 2
    Answer to self, and future readers: here is the list of typedefs for uintX_t class of type variables: `typedef unsigned char uint8_t;` `typedef unsigned int uint16_t;` `typedef unsigned long int uint32_t;` `typedef unsigned long long int uint64_t;` – narengi Jun 16 '15 at 00:11
  • 2
    @narengi: Which predefined types are used for the `[u]intN_t` types varies from system to system. That's why the the `[u]intN_t` types exist, because the sizes of the predefined types vary. `uint16_t` would be defined as `unsigned int` only if `int` is 16 bits, which is rare for hosted systems. – Keith Thompson Jun 16 '15 at 00:17
  • 1
    @KeithThompson I see your point. But the takeaway message for me was that [u]intX_t type variables are just typedefs, and are defines by various sorts of built-in types, ranging from char to int and long int, etc. and shold not be necessarily treated as integer types. But thanks for the clarification. – narengi Jun 16 '15 at 00:35
  • What happens when I pass "var" into a function? Do I also have to cast it to "(int)," or will the program pass the correct value outside of printing? Why does that happen, anyway? – Pototo Sep 01 '16 at 20:11
  • @Pototo If the function has a single overload that takes an `int`, you do not need a cast. `operator <<` has several overloads, one of which is for `char`. – Sergey Kalinichenko Sep 01 '16 at 20:47
  • Aight. C++ is a crazy languange – Pototo Sep 01 '16 at 21:05