Welcome! Log In Create A New Profile


Odd && Comparison

Posted by TPAINROXX 
Odd && Comparison
July 20, 2009 03:20AM
Hey, could anyone answer me this simple question? When I started learning C++ a few months ago I learned that when using a conditional statement that had &&, that this was the correct way to use it:

if ( x == 5 && y == 3)

But I've noticed that if I don't use just &, then the statements don't work correctly. For example (from my code):

		u32 held = WPAD_ButtonsHeld(0);
		if (held & WPAD_BUTTON_HOME)
		else if (held & WPAD_BUTTON_A)
		else if (held & WPAD_BUTTON_B)
		else if (held & WPAD_BUTTON_1)

If I used && then only the first part of the statement is read (just held) and not the second. I noticed this because I would hit A and it would bring up the exit_menu() (since it's the first conditional statement), but once I removed a & the code ran the way I intended. This isn't a major problem, but I also want to know if I need to use I instead of II.


I learned this from:
at logical operators.
Re: Odd && Comparison
July 20, 2009 03:37AM
& is the bitwise AND operator. Held is just a collection of 32 bits, and each bit represents a button. The buttons (WPAD_BUTTON_xx) are just variables where only the bit that determines whether a certain button was pressed is set to 1. The & will only return true if one of the bits "overlaps", or both are set to 1. This is kind of confusing, and hard to explain. Read up on bitwise operations here.
Re: Odd && Comparison
July 20, 2009 04:38AM
Thanks. I knew & was for bitwise I just didn't know exactly when to use it. But thanks again as it makes more sense...
Sorry, only registered users may post in this forum.

Click here to login