1

I have the following code in my project:

#include <iostream>
#include <cstdint>
#include <queue>

int main()
{
    std::queue<uint8_t> queue;
    queue.push(5);
    std::cout << queue.front() << std::endl;

    int8_t value = 10;
    std::cout << value << std::endl;
}

And when I print any of those values of type uint8_t or int8_t I get random output. When I print values of any other integer type from the cstdint I get the expected output. Random output only appears when I print the 8 bit values.

Note: I'm new to c++ programming as I recently started learning it.

  • 2
    `uint8_t` is treated like a `char` here. So it's printing character `5` and character `10`. You can see this in the disassembly [here](https://godbolt.org/z/WMGcbr) – ChrisMM Dec 22 '20 at 22:29
  • What ChrisMM said. Try cout << (int)value << endl instead. – Andy Newman Dec 22 '20 at 22:31
  • for directly printing an `uint8_t` that you know will be limited in range 0-9, you can just offset it by 0x30, otherwise (the recommended way for printing numerical values) is to use itoa functions from `` – Expolarity Dec 22 '20 at 22:31
  • @ChrisMM it does. Thanks for the help. – Duško Mirković Dec 22 '20 at 22:34
  • `uint8_t` is often implemented along the lines of `typedef unsigned char uint8_t;` You see `uint8_t`, but the compiler sees `unsigned char` and calls the `<<` overload for `unsigned char` – user4581301 Dec 22 '20 at 22:35
  • I do wonder how `uint8_t` would be implemented on one of the Crays of the old days where `char` was 32 bit like every other integral type. – user4581301 Dec 22 '20 at 22:38
  • @user4581301 The types `intN_t` and `uintN_t` are [optional](https://en.cppreference.com/w/cpp/types/integer), they are provided only if the implementation directly supports the type. – heap underrun Dec 22 '20 at 23:37
  • I suppose I deserved that for not specifying. Regardless, I'm still interested in how you could implement them. – user4581301 Dec 22 '20 at 23:45
  • @user4581301 I'm not sure I understand what you mean by "_how you could implement_". You couldn't, that's the point why those types are not required by the standard. On hardware with a 32-bit byte (here I'm using the term _byte_ in the sense how the C++ standard defines it, not in the common "byte is 8 bits" sense), the `int8_t`, `int16_t`, `uint8_t`, and `uint16_t` will not be implemented, and the corresponding typedefs will not be provided at all, as the standard suggests. (There will still be `int_fast8_t`, `uint_least16_t`,… there, but those will be 32-bit still.) – heap underrun Dec 23 '20 at 00:14
  • Agreed. Byte is `char`, so if `char` is 32 bits, byte is 32 bits. Anything you hacked out to implement int8 and int16 would be gross and inefficient with a butt-load of hidden bit-twiddling. But you also know someone's going to do it just to do it. – user4581301 Dec 23 '20 at 01:45

0 Answers0