Section 32.3 Combining Bitwise Operators and Enums
Bitwise operators and enums pair especially well together when each enum constant represents a single bit— a technique often used to represent a set of independent on/off options (called flags) packed into a single integer. For example:
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void) {
enum filePermissions {
READ = 1, //0001
WRITE = 2, //0010
EXECUTE = 4 //0l00
};
int myPermission = READ | WRITE;
if (myPermission & EXECUTE) {
printf("You can run this file.\n");
}
else{
printf("You cannot run this file.\n");
}
return 0;
}
Since
READ, WRITE, and EXECUTE each occupy a different bit position (\(0001\text{,}\) \(0010\text{,}\) \(0100\)), we can combine several permissions into one integer using bitwise OR (|), and later test whether a specific permission is set using bitwise AND (&)— all without needing a separate variable for each flag.

