[cfe-dev] uint8_t not getting output to cout?

Bruce Hoult via cfe-dev cfe-dev at lists.llvm.org
Tue Feb 12 22:56:20 PST 2019


It *is* an integer. And so is the '-' when you write:

std::cout << int(y) << '-' << int(m) << '-' << int(d) << std::endl;

The problem is more that C and C++ don't have a proper character type.
"char" is just a small integer. The only reason this line of code dos
what you expect is that someone decided to make operator<<(ostream&,
char) copy the bits of, say 0x41 directly to the stream buffer while
operator<<(ostream&, short) and operator<<(ostream&, int) convert
0x0041 or 0x00000041 to the string "65" before adding it to the stream
buffer.

printf() "works" because you explicitly asked it to convert all the
arguments to decimal strings by writing %d for the char arguments
rather than %c.

It would probably have been better design for the C++ library to give
operator<< similar behaviour for all of char, short, and int make you
write...

std::cout << y << "-" << m << "-" << d << std::endl;

... to get what you want, but someone wanted to save a couple of
memory loads and branches.

That is one of the things that Java and C# and D improve on. But C and
anything that wants to remain compatible with C is stuck with it.

On Tue, Feb 12, 2019 at 9:57 PM Shriramana Sharma <samjnaa at gmail.com> wrote:
>
> Dear me, you're right! But this is horrible! I am using uint8_t
> importing it from the “stdint” library because I think of it as an
> integer! Is there no way to get this treated as an integer?!
>
> (BTW D has a type `byte` for 8-bit integers as distinct from `char`
> for 8-bit characters: https://dlang.org/spec/type.html)
>
> --
> Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा 𑀰𑁆𑀭𑀻𑀭𑀫𑀡𑀰𑀭𑁆𑀫𑀸



More information about the cfe-dev mailing list