-6

I start working with the termcaps and i saw this kind of operation.

term.c_lflag &= ~(ICANON);

I know &= is a binary AND, and i am not very confortable with it.

Why didn't simply use = or make a #define, and what the &= ~ do ?

albttx
  • 3,444
  • 4
  • 23
  • 42

3 Answers3

5

Assuming ICANON is a bit-mask, i.e. an integer with bits set to represent some feature, that statement will make sure those bits are not set in c_lflag.

This is often called "masking off" those bits.

The operation is a bitwise AND with the bitwise inverse (~ is bitwise inverse).

So, if the value of c_lflag is 3 (binary 112) before the operation, and ICANON has the value 2 (binary 102), it will become 1 since it's bitwise-AND:ed with the value ~2 which has all bits set except bit number 1 (binary ...111012).

It could also be written more verbosely as

term.c_lflag = term.c_lflag & ~ICANON;

The parentheses around ICANON should not be needed.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

Your line remove the bit(s) of ICANON from term.c_lflag:

Assuming terms ares 4 bits long, if the value of ICANON is 4 (0100b), then the value of ~ICANON is 11 (1011b), and so:

    term.c_lflag  1 1 1 0
AND      ~ICANON  1 0 1 1
    ---------------------
                  1 0 1 0

==> 1010b, 10 in decimal

Sylvain P.
  • 153
  • 6
0
term.c_lflag &= ~(ICANON);

is equal to

term.c_lflag = term.c_lflag & ~(ICANON);

& and ~ operators are two distinct operators. ~ is NOT operator in which it converts each bit with its inverse. & operator is bitwise AND operator in which it compares operands bit by bit.

Sabri Özgür
  • 632
  • 5
  • 10