C++ enum of type char, ignored by the compiler or unexpected behaviour? -
i did little test enum, here have:
enum anyoldname : char { aa = 'a', ab = 'b', ac = 'c', ad = 'd' }; int main() { anyoldname i_have_an_enum_here = aa; // expect i_have_an_enum_here of type char? std::cout << i_have_an_enum_here << std::endl; return 0; }
output is: 98
, unless cast explicitly char so:
std::cout << (char)i_have_an_enum_here;
or change anyoldname
char
.
why value 98
printed instead of b
?
by way sizeof()
returns 1
, ie; 1 byte, char
.
without cast, compiler first searches appropriate member function of std::ostream
, , finds 1 -- 1 int
. implicitly converts 1-byte number of type anyoldname
int
, calls member function.
compiling program g++ 4.8.1, 2 definitions ostream::operator<<
seen:
u std::ostream::operator<<(std::ostream& (*)(std::ostream&))@@glibcxx_3.4 u std::ostream::operator<<(int)@@glibcxx_3.4
the first 1 endl
, second 1 enum.
with explicit cast char, compiler able find perfect match in global std::operator<<
function takes ostream
, char
input. uses function rather doing implicit cast (to int
again) in order call ostream
member function.
the 2 symbols become:
u std::ostream::operator<<(std::ostream& (*)(std::ostream&))@@glibcxx_3.4 u std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char)
and values printed characters rather decimal values.
Comments
Post a Comment