C Programming · Interview question

Your code reads a register field with if (reg & MASK == 0) and it never matches. Why?

A strong answer

Operator precedence. == binds tighter than &, so reg & MASK == 0 parses as reg & (MASK == 0). MASK == 0 is almost always false (0), so the expression becomes reg & 0, which is always 0, the condition never matches. The fix is explicit parentheses: if ((reg & MASK) == 0). This is one of the most common bit-manipulation bugs in C, and it's why experienced firmware engineers reflexively parenthesize any bitwise operator that sits near a comparison or equality operator. Turning on -Wparentheses makes the compiler warn about exactly this pattern.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Bit Manipulation & Masks

Set, clear, toggle, and test individual bits without disturbing their neighbors: the read-modify-write idioms behind every GPIO and peripheral driver.

More Bit Manipulation & Masks questions

Browse all 472 interview questions
Your code reads a register field with if (reg & MASK == 0) and it never matches. Why? | EmbeddedPrep.io