x!=x vs x=!x

Hello, why x!=x doesn't equal x=!x?
1
2
3
4
5
6
7
8
int main()
{

bool b=true;
b!=b;  // == true , but I thought b!=b == false
b=!b;  // == false

}

Then I thought that b!=b should become b=b!b; (because a+=a equals a=a+a) but b=b!b; doesn't even compile. Shouldn't the compiler generate an error here?

Thanks for help.
Last edited on
In c++ comparisons have a logical value so b!=b will always be true.Cheers.
x=!x assigns the negated value of x to x.
x!=x evaluates to true if x is different from x. Obviously, a value can't be different from itself, so unless x is an object that overload operator!=() in a special way, x!=x always evaluates to false.
x!x doesn't compile because ! is a unary operator. It only accepts one operand.
Hello Null,

1
2
b!=b; // <--- this compare operator != (if and the like)
b=!b; // <--- assignment (=) and not (!) operator 


EDIT: too late but b!=b is always false
Last edited on
I find that whitespace helps clarify also...
x  !=  x     this is the 'not-equal' operator
x  =  !x     this is the 'assignment' operator followed by the 'logical-not' operator

:-)
EDIT:
this is the 'not-equal' operator

If so, shouldn't this code display 1?

1
2
3
4
5
6
7
8
9
10
int main()
{

bool x=false;
bool y=true;

x!=y; // true  == false not_equal true?
cout <<x<<endl; // outputs 0

}

Last edited on
!= compares two values, it doesn't modify values:
1
2
3
// int a, b
if ( a != b )
    // a and b are not equal 

http://www.cplusplus.com/doc/tutorial/operators/
What the...? How didn't I notice that ???
...

Thanks!
Sorry, instead of 'not-equal' I should have said 'inequality'. :-\
Topic archived. No new replies allowed.