2

For example, in this code:

#include <iostream>

int main()
{
    enum:char
    { a = 'a', b = 'b', c = 'c', NEWLINE = '\n' };

    std::cout << a << b << c << NEWLINE;
    return 0;
}

a, b, c, and NEWLINE print out as ASCII codes.

I am learning C++, and so far I understand pretty much everything I have studied. I know that enumerated types hold constant integral values, but I did not expect a value of type char to be displayed as an integral value (at least not without having to explicitly cast it).

I am curious why this occurs with enumerations? I have not been able to find a reason for why this is happening.

pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
j_burks
  • 93
  • 5
  • I can't see why both GCC and Clang would do that given *A prvalue of an unscoped enumeration type whose underlying type is fixed (7.2) can be converted to a prvalue of its underlying type. Moreover, if integral promotion can be applied to its underlying type, a prvalue of an unscoped enumeration type whose underlying type is fixed can also be converted to a prvalue of the promoted underlying type.* – chris Apr 12 '15 at 01:08
  • 1
    Ah, I found this: http://stackoverflow.com/questions/14206403/why-does-a-value-of-an-enum-with-a-fixed-underlying-type-of-char-resolve-to-fct – chris Apr 12 '15 at 01:14
  • Interesting. Well, I'm glad it wasn't just me who was surprised by this behavior. I suppose there's no use in using an 8-bit fixed-width integer as the enumeration's type when a char will do. – j_burks Apr 12 '15 at 01:29
  • `char` is actually a numeric type whose values are usually interpreted as characters in the local charset encoding. – Ignacio Vazquez-Abrams Apr 12 '15 at 01:54
  • closing as duplicate: it is the same because the `<<` operator here is a function call `operator<<` and so it is exactly the same issue as the other thread, as to whether the `char` overload or the `int` overload is called. – M.M Apr 12 '15 at 02:18

0 Answers0