0

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?

Jeroen Ooms
  • 31,998
  • 35
  • 134
  • 207
  • What is the result of `4 | 4` and `4 + 4`? You need to read about [Bitwise Operators](http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/bitwise.html) – Iharob Al Asimi May 27 '15 at 11:21
  • BTW, why do not use loop and keep options as array of pairs name -> mask. – myaut May 27 '15 at 11:22
  • Ok thanks I get it now. The benefit of `|=` is that it is idempotent if the same argument is specified twice. Otherwise `--sourcepos --sourcepos` would equal `--hardbreaks` which makes no sense. – Jeroen Ooms May 27 '15 at 11:30
  • @Jeroen: if `--sourcepos` may be specified more than once, you may reserve multiple bits for it and use `+=` for it. For example, `preempt_count` in Linux works like this (a single word with multiple counters inside). – myaut May 27 '15 at 12:14

0 Answers0