0

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){
...
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39

2 Answers2

1
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.

Dan Bonachea
  • 2,408
  • 5
  • 16
  • 31
1

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.

hyde
  • 60,639
  • 21
  • 115
  • 176