I was reading some tutorial about openGL in qt.
One of the mouse event slot has this code in it:
if (event->buttons() & Qt::LeftButton) {
rotationX += 180 * dy;
rotationY += 180 * dx;
updateGL();
}
what does the & operator do in the if statement?
is it exactly the same as == ?
It is not the same as
==. It is bitwise AND operator. What the expression does is that it takes the return value fromevent->buttons()and bitwise AND‘s it with the value represented byQt::LeftButton. If the resulting value is non-zero the block is being executed.In essence, it checks if the button specified by
Qt::LeftButtonis held down.The reason why the
bitwise ANDoperator is used here is something called a bitmask. What it means is that the return value ofevent->buttons()is just a value which has it’s bits represent different kinds of states. What is done with the &-operator here is that it checks if certain bits(denoted byQt::LeftButton) are being set(1) or unset(0) in the value returned byevent->buttons(). The return value is zero if no tested bit is set, and non-zero, if at least one of the tested bits is set.More details of how bitwise operations work can be found here: Wikipedia article about Bitwise operations