Game Development Reference
In-Depth Information
6.1E NUM F LAGS
This section is intended as an introduction to bitwise operations using flags, it's a useful
idiom that can greatly simplify code that allows for multiple conditions to be satisfied or
excluded. Many beginner programmers fall into the trap of writing very complex conditions
using Boolean flags, in many cases this leads to unwieldy code. During production as fea-
tures evolve and more variables come into play, the condition tests become more and more
complicatedtothepointthatittakesmoretimetounderstandhowtotestforanewcondition
without breaking the existing tests than it would be to implement the feature. Enum flags
provide a way to test forsingle ormultiple conditions without a great deal ofcomplexity for
the user.
An enum by default represent an int, C++11 gives us the ability to specify the size of the
type we wish it to be, it can be signed or unsigned. For our discussion on enum flags, we
will be using a 32-bit unsigned integer as the size of the enum. The first part to understand
is which values need to be assigned to the elements of the enum in order to have the ability
to perform bitwise operations on them.
There are three different ways in which an enum could be constructed to be used as flags,
they are all equivalent and usually are chosen by programmer preference or coding conven-
tion.
enum {
FLAG0 = 0x01,
FLAG1 = 0x02,
FLAG2 = 0x04,
FLAG3 = 0x08,
FLAG4 = 0x10,
FLAG5 = 0x20
};
enum {
FLAG0 = 1,
FLAG1 = 2,
FLAG2 = 4,
FLAG3 = 8,
FLAG4 = 16,
FLAG5 = 32
};
enum {
FLAG0 = (1<<0),
FLAG1 = (1<<1),
FLAG2 = (1<<2),
FLAG3 = (1<<3),
FLAG4 = (1<<4),
FLAG5 = (1<<5)
};
If we see the binary representation of the flags, we see that they are all one bit apart.
Search WWH ::




Custom Search