I am having trouble understanding what the purpose of the &
means in this if statement. Would anyone be willing to point me in the right direction? I thought struct calls go as follows
car -> model == "jeep"
This is what I am having confusion about:
if ((x->status & 1) == 0){
...
}
CodePudding user response:
if ((x->status & 1) == 0){ ... }
This code retrieves the value of the status
field from the struct pointed to by x
, and performs a bitwise and operation against the constant 1, which has the effect of masking off all but the least significant bit. As a result, this code is checking whether the least-significant bit of the field's value is zero.
CodePudding user response:
This
if ((x->status & 1) == 0){ ... }
Is same as
unsigned status = x->status;
unsigned status_bit0 = status & 1;
if (status_bit0 == 0) { ... }
And single &
with two operands (on both sides) is bitwise AND operator, not to be confused with unary &
which is address-of operator and completely unrelated. Learn binary numbers to understand what bitwise AND is and how it can be used to extract a single bit, that's too broad a subject for this answer.
Also note that unsigned
may be wrong type, use what ever is the type of the strict field.