Reputation: 173
I wrote this program:
#include <iostream>
using namespace std;
void unequalityOperator(){
cout << "Running unequalityOperator..." << endl;
bool a = true, b = false;
if ( a != b ) cout << "!=" << endl;
if ( a =! b ) cout << "=!" << endl;
}
int main()
{
unequalityOperator();
system("pause");
return 0;
}
And I was surprised that it run and printed both of the strings. So I tried the same thing with some other binary operators like <=
, >=
, etc. but it didn't work.
Therefore I would like to understand whether there is a difference between !=
and =!
.
I do know that there are some operators like +=
, -=
, etc. that work differently and, e.g., the difference between +=
and =+
is that the addition will occur before or after (respectively) the actual command. And for this reason I suspect that there is difference with the hierarchy in the implementation of these operators, but I am not really sure what.
So please help me understand.
Upvotes: 0
Views: 170
Reputation: 32542
This might help to clear things up:
!=
: not-equal operator=!
: these are really two operators: assignment operator and unary logical NOT operator+=
: sum-assignment operator=+
: these are really two operators: assignment operator and unary + operator-=
: difference-assignment operator=-
: these are really two operators: assignment operator and unary - operatorAlso, as these were in your question before being edited out:
++=
: two operators: postfix increment operator and assignment operator=++
: two operators: assignment operator and prefix increment operatorI hope you notice the pattern.
For reference:
Upvotes: 0
Reputation: 18381
In first case the !=
operator is a single inequality operator. In second case it is an assignment operator =
with logical not operator !
. So in the second case you are assigning not b
to a
and returning it's result true
Upvotes: 1
Reputation: 30146
The expression a = !b
is an assignment of the value !b
into the variable a
.
The evaluation of this expression within an if
statement is the new value of a
.
Since b
is set to false
and you are assigning !b
into a
, this value is true
.
Upvotes: 3