What does &= mean?

user3165140 picture user3165140 · Jan 6, 2014 · Viewed 23.2k times · Source

I'm using termcaps and I don't understand what &= means in this example:

term.c_lflag &= ~(ICANON);

Could anyone explain to me how this works?

Answer

Kos picture Kos · Jan 6, 2014

That's a common way to set a specific bit to 0 in an integer that represents a bitfield.

unsigned a = ...;
// ...
unsigned int mask = 1 << 11;  // mask for 12th bit
a |=  mask;  // set 12th bit to 1
a &= ~mask;  // set 12th bit to 0

Enabling a bit works by bitwise-oring a number with a mask that looks like 000010000.
Disabling a bit works by bitwise-anding a number with a mask like 111101111 (hence the need for ~, which stands for bitwise negation).

Note that there are also other options for managing bitfields:

  • in C++, using std::bitset or even std::vector<bool>
  • in C or C++, using a bitfield struct like

    struct Foo {
       int foo_enabled : 1;
       int bar_enabled : 1;
       // ...
    };