0

I have an enum like (this is just an example):

enum tStates
{
    STOP            = (1<<0),
    PLAYING         = (1<<1),
    SYNCHRONISING       = (1<<2),
    READY_TO_PLAY       = (1<<3),
    CONNECTED       = (1<<4),
}

So it can be playing and connected at the same time etc... Multiple states at once is possible. I need to test different states, for instance:

if (m_pDeviceHealth->getHealth().isSet(PLAYING))
{


}
else if (m_pDeviceHealth->getHealth().isSet(STOP))
{


}

It tends to become quite big and difficult to read.

Is there a clearer way to check for a flag? Is it possible to use a switch for instance?

dyesdyes
  • 1,147
  • 3
  • 24
  • 39

2 Answers2

2

Actually I don't know how the actual flag checking should be made simpler without your data structures or what you want to do with that. Basically what you have is:

if (m_pDeviceHealth->getHealth().isSet(PLAYING))
    | your expression           |      |your flag|

Seems quite minimal to me. For different flags you'll obviously need different if branches. If you are looking for checking if any of multiple bits is set, you can use bit masking like:

if (m_pDeviceHealth->getHealth() & (PLAYING | SYNCHRONIZING))

under the assumption that getHealth is an integer.

dornhege
  • 1,500
  • 8
  • 8
0

It's not nice but if you are looking for a switch, you can do flag combination yourself in cases:

switch (m_pDeviceHealth->getHealth().getValue()) {
   case PLAYING:
      // ...
      break;
   case STOP:
      // ...
      break;
   case CONNECTED:
   case SYNCHRONISING:
   case SYNCHRONISING|CONNECTED:
      // ...
      break;
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Oleg Fedorov
  • 337
  • 3
  • 10
  • 1
    Is it even going to work as it's supposed to check only one bit? – dyesdyes Jan 31 '14 at 11:53
  • Did you even bother to try this? – Lightness Races in Orbit Jan 31 '14 at 12:02
  • 1
    @LightnessRacesinOrbit what's wrong? I think he wanted to point out that you can use bitwise operators in `case` statements like `case SYNCHRONISING|CONNECTED`. But I think it's not really 'clean' ... – Gerrit-K Jan 31 '14 at 12:07
  • 1
    I wrote that it is not nice - you need to have case for every possible combination of flags. So, if PLAYING can be combined with CONNECTED then you need to have case for PLAYING|CONNECTED. But questions asks for switch - here is a switch – Oleg Fedorov Jan 31 '14 at 12:07
  • @OlegFedorov: Heh, well, fair enough ;) – Lightness Races in Orbit Jan 31 '14 at 12:10
  • Your code doesn't do exactly what his does, since if `PLAYING` is set, he won't test any of the other cases. To do this in a switch, you'd have to start with all of the combinations which contain `PLAYING` (followed by the action and a `break`), then all of the combinations which contain `STOP`, but don't contain `PLAYING`, and so on. – James Kanze Jan 31 '14 at 12:30