C Programming · Interview question

Why should you write 1u << n instead of 1 << n for a mask?

A strong answer

1 is a signed int. Shifting a 1 into or past the sign bit is undefined behavior, 1 << 31 on a 32-bit int shifts into the sign bit, which the standard declares UB (and 1 << 32 or more is UB regardless). 1u is an unsigned int, and unsigned left shifts are well-defined to wrap modulo 2^width, so 1u << 31 cleanly produces 0x80000000. Since masks frequently target high bits, 1u << 31 for the top bit of a 32-bit register is routine, using the unsigned literal is necessary for correctness, not just style. For 64-bit masks you'd go further with 1ull << n. The habit of always making shift operands unsigned eliminates a whole class of subtle, optimization-level-dependent bugs.

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
Why should you write 1u << n instead of 1 << n for a mask? | EmbeddedPrep.io