|= Operator

Hi, I am using the following lines of code in my program:

bool notOk = false;
notOk |= (newMouse.x==40 && newMouse.y==12);
notOk |= (newMouse.x>72 && newMouse.y<3);
notOk |= (mice[j].x == newMouse.x && mice[j].y == newMouse.y);

If any of the 3 conditions are true, I want notOk to be true by the end of the sequence, even if the other 2 are false. Is this the correct way to do this? I am using what little I know of boolean algebra, my professor showed this in a class example.

Thanks for your help!

Best,
Scot
First of all the variable name is atrocious. It results in a double negative during interpretation of the meaning. Notok=false is the same as ok=true but the latter is much easier to read.
1
2
3
bool condition = ( (newMouse.x==40 && newMouse.y==12) ||
                         (newMouse.x>72 && newMouse.y<3) ||
                         (mice[j].x == newMouse.x && mice[j].y == newMouse.y));


What you did appeared to be consistent with your requirements. However it could have been done in one statement. | is the boolean OR operation. || is a conditional test which accomplishes the same thing but within one statement. I think that using the single statement is more efficient because the conditions don't all have to be evaluated. If the first group of conditions is true, the rest do not have to be executed at all. The way you had done it would require all three sets of conditions to be evaluated regardless of which turned out to be true.
Yes, I know the double negatives are quite confusing, but we are required to use the code because our professor is trying to make things hard for us ^^.
Your version is much better and more compact, thanks!
hello scotfang,


|
The bitwise-inclusive-OR operator compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


vs


||
The logical-OR operator performs an inclusive-OR operation on its operands. The result is 0 if both operands have 0 values. If either operand has a nonzero value, the result is 1. If the first operand of a logical-OR operation has a nonzero value, the second operand is not evaluated.


I don't think that you want that 'bitwise or'.
Topic archived. No new replies allowed.