I''ll make it simpel. Or maybe not.
The states are defined as STATE_1 = 1, STATE_2 = 2 and STATE_3 = 4.
x = STATE_1 | STATE_2 | STATE_3; // x = 0111 (binary)
Let''s say you want to check if STATE_1 and STATE_2 is set for x. Doing it with if would look like this:
if( x & (STATE_1 | STATE_2) == (STATE_1|STATE_2) )
// The left of ''=='' is "0111 & (0001 | 0010)" which means "0111 & 0011" and that in turn means "0011"
// The right of ''=='' is simply 0011 (0001 | 0010)
// The gives us, 0011 == 0011 which is true
// I would have used "if( x & STATE_1 && x & STATE_2 )" for doing this though, this was just an example
// Here x still is 0111
switch( x )
{
case (STATE_1 | STATE_2): // This is the same as "case 0011:" 0011 is binary, just so there will be no misunderstandings
// Now switch will compare x with the case by using something similiar to "if( x == y )" which would
// give us:
// if( 0111 /*binary value of x*/ == 0011 /*binary value of the case*/ )
// As you can see this is not true. And yes, I do know that you can''t use binary values like that. It was
// just for the example
}
Then you say that "Benny''s incorrect. You can use a switch. He didn''t include a case for all three set.". Now, why didn''t I do that?
1) I wanted to show that you cannot check for, as in my example, two bits only. Of course you can include all possible cases in that switch statement. But if you have 32 bits that can be set. I don''t care to count the number of possible cases but I''m sure you don''t want to sit there and write them all -- Use if instead.
2) If included a check for STATE_1 it would look something like this:
case STATE_1:
case STATE_1 | STATE_2:
case STATE_1 | STATE_3:
case STATE_1 | STATE_2 | STATE_3:
Then there''s one check like that for STATE_2 and STATE_3 plus (STATE_1 | STATE_2), (STATE_1 | _STATE_3), (STATE_2 | STATE_3) and finally (STATE_1 | STATE_2 | STATE_3).
3) Ok, it''s POSSIBLE to do it. But at the same time it''s not, not if you want to do something else than write cases at least. But! It is still not possible to perform a bitwise comparison in a case statement. It is possible to twist my words and missunderstand a thing or two to prove me wrong
Try doing "if( x & (STATE_1 | STATE_2) )" with "case (STATE_1 | STATE_2):" and you will fail every time.
Well, that''s it about that. I''m going to read Winter''s Heart now
-Benny-