Flags
Last updated on
You’ll see API’s use flags alot, they are a great way of storing multiple options in a single variable. Then you can query the variable to see if the option has been set.
/* flags.c */
#include <stdio.h>
/* flags must be power of two */
enum flags {
OPT_RESIZE = 1 << 0,
OPT_CLOSE = 1 << 1,
OPT_DRAG = 1 << 2,
OPT_MIN = 1 << 3,
};
int
main() {
/* use bitwise 'or' to combine the options */
int opts = OPT_RESIZE | OPT_DRAG | OPT_MIN;
/* then we can check for flag(s) with '&' */
if(opts & OPT_RESIZE) {
printf("Resize supported\n");
}
if(opts & (OPT_DRAG | OPT_MIN)) {
printf("Drag and Minimize supported\n");
}
if(opts & OPT_CLOSE) {
printf("Close supported\n");
}
return 0;
}
Compile and run,
gcc flags.c && ./a.out
outputs …
Resize Supported
Drag and Minimize supported