Using |= for CLI argument parsing

52 views Asked by At

The CLI in main.c of cmark uses the |= operator for combining on/off options when iterating over arguments. A simplified version looks like:

#define CMARK_OPT_DEFAULT 0
#define CMARK_OPT_SOURCEPOS 1
#define CMARK_OPT_HARDBREAKS 2
#define CMARK_OPT_NORMALIZE 4
#define CMARK_OPT_SMART 8

int options = CMARK_OPT_DEFAULT;

for (i = 1; i < argc; i++) {
    if (strcmp(argv[i], "--sourcepos") == 0) {
        options |= CMARK_OPT_SOURCEPOS;
    } else if (strcmp(argv[i], "--hardbreaks") == 0) {
        options |= CMARK_OPT_HARDBREAKS;
    } else if (strcmp(argv[i], "--smart") == 0) {
        options |= CMARK_OPT_SMART;
    } else if (strcmp(argv[i], "--normalize") == 0) {
        options |= CMARK_OPT_NORMALIZE;
    } 
    ...
}

What is the benefit of using |= and not += to add up the options?

0

There are 0 answers