Flags
Flags are single-bit independent data that are kept together in the same variable. As they are only one bit wide each, they are suitable for representing binary concepts like enabled/disabled, valid/invalid, etc.
We sometimes encounter such one-bit concepts in D modules that are based on C libraries.
Flags are usually defined as non-overlapping values of an enum type.
As an example, let’s consider a car racing game where the realism of the game is configurable:
-
The fuel consumption is realistic or not.
-
Collisions can damage the cars or not.
-
Tires can deteriorate by use or not.
-
Skid marks are left on the road surface or not.
These configuration options can be specified at run time by the following enum values:
enum Realism {
fuelUse = 1 << 0,
bodyDamage = 1 << 1,
tireUse = 1 << 2,
skidMarks = 1 << 3
}
Note that all of those values consist of single bits that do not conflict with each other. Each value is determined by left-shifting 1 by a different number of bits. The corresponding bit representations are the following:
fuelUse : 0001
bodyDamage: 0010
tireUse : 0100
skidMarks : 1000
Since their 1 bits do not match others’, these values can be combined by the |
operator to be kept in the same variable. For example, the two configuration options that are related to tires can be combined as in the following code:
Get hands-on with 1400+ tech skills courses.