public inbox for libstdc++@gcc.gnu.org
 help / color / mirror / Atom feed
* operator<< and int8_t and uint8_t types....
@ 2023-10-23 11:36 Théo Papadopoulo
  2023-10-23 11:45 ` Jonathan Wakely
  0 siblings, 1 reply; 4+ messages in thread
From: Théo Papadopoulo @ 2023-10-23 11:36 UTC (permalink / raw)
  To: libstdc++

     Hi,

I suspect that this will probably receive an answer "this is the 
intended/normal/expected  behavior", but from what I saw on the internet
this is a kind of gray area in the standard and I did not found any 
(even closed) report on bugzilla, so I thought of asking here.

Currently, printing a int8_t of uint8_t number with operator<< basically 
prints it as a (u)char. I think this is very unfortunate and is somewhat 
deceptive to
users which expect a "int" like behavior.

#include <iostream>
#include <cstdint>

namespace std {

     std::ostream& operator<<(std::ostream& os,const int8_t v) {
         return os << static_cast<int>(v);
     }

     std::ostream& operator<<(std::ostream& os,const uint8_t v) {
         return os << static_cast<int>(v);
     }
}

int main() {
     std::int8_t a  = 65;
     std::uint8_t b = 66;
     char         c = 'c';
     std::cerr << a << ' ' << b << ' ' << c << std::endl;
}

Without the operator<< overloads: this code prints:

A B c

whereas I think a programmer would expect to see:

65 66 c

which is what is obtained with the overloads.

There is an old and extended discussion on stack overflow on the 
subject, in which from some comment it seems that
it is the promotion to int vs the conversion to char that plays a role 
here (and that gcc like many over compiler favors the char
conversion over the int promotion, but I'm not so sure about the 
validity of this discussion).

Certainly from the user's perspective, one would expect to see and 
integer value and not a char... and it does not look very difficult to do.

     Thank you in advance,

         Theo.






^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2023-10-23 12:01 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-10-23 11:36 operator<< and int8_t and uint8_t types Théo Papadopoulo
2023-10-23 11:45 ` Jonathan Wakely
2023-10-23 11:53   ` Jonathan Wakely
2023-10-23 12:01     ` Jonathan Wakely

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).