Search code examples
cbinarytermcap

What is this operation in C?


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 ?


Solution

  • 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.