5

I have got the enum

enum ProgramID
{
    A = 0,
    B = 1,
    C = 2,
    MIN_PROGRAM_ID = A,
    MAX_PROGRAM_ID = C,

} CurrentProgram;

Now, I am trying to increment CurrentProgram like this: CurrentProgram++, but the compiler complains: no 'operator++(int)' declared for postfix '++' [-fpermissive]. I think there IS such an operator that increments "enums", but if there is not, how do I get the successor of one of these values?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
HerpDerpington
  • 3,751
  • 4
  • 27
  • 43
  • So what do you think would be the successor of `B`? `C` or `MAX_PROGRAM_ID`? And what would be the successor of `C`? – orlp Dec 24 '13 at 18:01
  • the next value: 1 -> 2, 2 -> 3 etc... – HerpDerpington Dec 24 '13 at 18:03
  • 1
    @BenjaminLindley I think the Problem is not the same... – HerpDerpington Dec 24 '13 at 18:06
  • 1
    Technically you're right, it's not. Your problem is that you think there is an operator which increments enums. So, technically, the solution to your problem is to simply tell you "no, you are wrong, there is no such operator." I just figured that the question I linked to, and its answers, would be much more useful to you or anyone else with this same problem. – Benjamin Lindley Dec 24 '13 at 18:09
  • @user1574054: Just make your own `operator++` for the `enum`. Though you'll have to find some way to deal with doing ++ when the enum is already maxed out; you could wrap-around, but that's not exactly an intuitive use of ++. – Cornstalks Dec 24 '13 at 18:19
  • @Cornstalks wrap-around of incrementing an enum may not make sense in some ways, but it would at least be somewhat consistent with what happens in most implementations when you overflow an integer type by incrementing... – twalberg Dec 24 '13 at 18:58

2 Answers2

5

There is no such an operator for enumerations. But you can write that operator yourself. For example

ProgramID operator ++( ProgramID &id, int )
{
   ProgramID currentID = id;

   if ( MAX_PROGRAM_ID < id + 1 ) id = MIN_PROGRAM_ID;
   else id = static_cast<ProgramID>( id + 1 );

   return ( currentID );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

No, you are wrong, there is no such operator.

To get the next one, convert your value to an int, increment it, then reinterpret_cast it back to your enum. Note that going out of bounds can eventually lead to undefined behaviour, so checks are a good idea.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524