Minor confusion about booleans

This is a problem I should know the solution to… :persecutioncomplex: I might have forgot it, because I know I’ve faces this before, where I’ve
had to hack it!

Alright. You have too booleans, and you want to execute a void if at least one of them returns true. How do you do that without using a couple of if-statements, or the longest if-statement ever? I see both using a couple of if’s, and making an if so long that you need to scroll, as hacks and I would like to know the correct way to solve this, or go around it. :smiley:

[quote=“Mads,post:1,topic:36628”]
Can you explain that?


boolean a = ...;
boolean b = ...;
if( a || b )
{
    // void??
}

I expect he means he wants to call a method with a void return type.

Exactly!


if (a || b) {
}

What if both are true?

That if-case means “if either a or b is true, run this block”. Since both of them are true, it will run the block. The only way to make it not run the block is if both a and b are false.

Oh lord… I’ve always been taught that those ment OR… If a OR b is true… not both… :emo:
I’ll go back into my cave now. Thanks! ::slight_smile:

for that we have XOR (exclusive OR)

if( a ^ b )
{

}

I always had problems using that correctly… I imagine that operator does something different to ints :stuck_out_tongue:

Maybe I’m just tired or something, but doesn’t this code give the same result?

if(a != b) {

}

Is there any advantage of using one over the other?

In this case they are equal

the xor rules :

0 ^ 0 => 0
0 ^ 1 => 1
1 ^ 0 => 1
1 ^ 1 => 0

so, for instance 1101 ^ 110 = 1011

But, I must say that the only case I found it useful to use is to make a variable switch between 1 and 0.

I think in y86 (maybe other ASM languages ?) XOR is used to set 0 to a registry, because a ^a = 0, and it is quicker to do a XOR than to get the constant value in memory

Perhaps we are getting a bit off topic, but XOR can also be used for swapping values of two variables without the use of an extra variable. So in theory it has many uses…
This page also seems to have related information: http://stackoverflow.com/questions/160697/is-it-good-practice-to-use-the-xor-operator-in-java-for-boolean-checks

  • Scarzzurs

Thanks for the link. I have never used xor before (have heard of though) but that cleared up some question marks for me :slight_smile: