What's this =! operator? [duplicate]

I was surprised by this code:

if (a =! b) { // let it be on false
    ...
}

But a is never assigned by a value. What's this operator about?


That's two operators, = and !, not one. It might be an obfuscated way of writing

a = !b;
if (a) {
    // whatever
}

setting a to the logical inverse of b, and testing whether the result is true (or, equivalently, whether b was false).

Or it might be a mistyping of a != b.


Long ago, when dinosaurs roamed the earth and C ran on 5th edition UNIX on PDP-11s, =! was the 'not equals' operator. This usage was deprecated by the creation of Standard C, so now it means 'assign the logical inverse', as in a = !b. This is a good argument for always surrounding binary operators with spaces, just to make it clear to the humans reading the code what the compiler is thinking.

I'm a bit surprised nobody else mentioned this, but then again I may be the only SO user to have ever touched a C compiler that old.


a is assigned the boolean negation of b in that line. It is just a misformatted

if( a = !b ) {

... and an evil hidden assignment inside a condition.


a =! b 

is just a funny way of putting

a = !b

i.e. the assignment of not b to a.

The value of the expression is a after the assignment.

With the code below you can see that the value of the expression a = !b is !false (i.e. true), and you can then see the assignment has taken place by checking the value of a, which is also true.

#include <iostream>

int main() 
{ 
    bool a = false;
    bool b = false;

    if(a)
        printf("a is true!\n");
    else
        printf("a is false!\n");

    if(a = !b)
        printf("expression is true!\n");
    else
        printf("expression is false!\n");

    if(a)
        printf("a is true!\n");
    else
        printf("a is false!\n");

}

Result:

a is false!
expression is true!
a is true!

Operators in C++

According to C/C++ operators list there is no operator such as =!. However, there is an operator != (Not equal to, Comparison operators/relational operator)

There are two possibilities.

  1. It could be typo mistake as I've noticed that =! operators is in if statement and someone is trying to type != instead of =! because != is the comparison operator which returns true or false.
  2. Possibly, the developer was trying to assign the boolean negation of b to a and he/she has done a typo mistake and forgot to put a space after equal sign. This is how the compiler interprets it, anyways. According to Operator precedence in c++:
    • Operator Logical NOT (!) precedence is 3 and Associativity is Right-to-left
    • Operator Direct assignment (=) precedence is 16 and Associativity is Right-to-left