Topic: Can enumerated types be incremented?
Author: stephen.clamage_nospam@eng.Sun.COM (Steve Clamage)
Date: 1997/12/18 Raw View
On 09 Dec 97 05:29:22 GMT, "Piet Van Vlierberghe" <pvv@lms.be> wrote:
>As far as I can tell from the ANSI standard proposal, adding to an
>enumerated type using e.g. the += operator is allowed, but incrementing
>using the prefix or postfix operator ++ is not. Is there a good reason for
>this, or did I misread the standard?
None of the operations are valid, so I think you misread the standard.
(Some rules about enumerated types and overloading have been tweaked
recently, but I think what I present below has always been true.)
Enumerated types can be used in arithmetic expressions via promotion
to integral types, but they are not themselves arithmetic types. The
various built-in arithmetic operations (+, - *, /, %) apply to
arithmetic types (and in some cases to pointers) but not to enumerated
types. In any assignment expression, the value on the right is
implicitly converted to the type of the target on the left. If no such
implicit conversion is available, the assignment is invalid.
(Refer to 3.9 "Types", 4 "Standard conversions", 5.7 "Additive
operations", and 5.17 "Assignment operations".)
Example, for variables e1 and e2 of some enumerated type E:
e1 += e2; // #1, error
e1 -= 1; // #2, error
e1 = E(e1 + e2); // #3, ok
e1 = E(e1 - 1); // #4, ok
The expression (x+=y) is equivalent to (x=x+y), except that x is
evaluated only once. Addition is not defined for enumerated types, so
in #1 and #3 the values of enumerated type are promoted to some
integral type and are added. The result has an integral type. There is
no implicit conversion from integral to enumerated type, so #1 doesn't
work, but #3 is OK because of the explicit cast. The same holds for
subtraction, explaining #2 and #4.
---
Steve Clamage, stephen.clamage_nospam@eng.sun.com
( Note: remove "_nospam" when replying )
---
[ comp.std.c++ is moderated. To submit articles: Try just posting with your
newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
Comments? mailto:std-c++-request@ncar.ucar.edu
]
Author: "Piet Van Vlierberghe" <pvv@lms.be>
Date: 1997/12/09 Raw View
As far as I can tell from the ANSI standard proposal, adding to an
enumerated type using e.g. the += operator is allowed, but incrementing
using the prefix or postfix operator ++ is not. Is there a good reason for
this, or did I misread the standard?
Thanks in advance.
pvv@lms.be.NOSPAM
---
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]