Using bit shift operators in an enum
As we have seen before in previous recipes, an enum is used to represent a collection of states. All the states are given an integer value by default, starting at 0
. However, we could specify a different integer value as well. More interestingly, we could use bit shift operators to club some of the states, easily set them to be active or inactive, and do other tricks with them.
Getting ready
To work through this recipe, you will need a machine running Windows with an installed Visual Studio.
How to do it…
In this recipe, we will see how easy it is to write bit shift operators in an enum:
#include <iostream> enum Flags { FLAG1 = (1 << 0), FLAG2 = (1 << 1), FLAG3 = (1 << 2) }; int main() { int flags = FLAG1 | FLAG2; if (flags&FLAG1) { //Do Something } if (flags&FLAG2) { //Do Something } return 0; }
How it works…
In the above example, we have three flag states in the enum. They are...