← Exercises|

The precedence trap that bites everyone

Predict6 of 14 · about 5 min

The precedence trap that bites everyone

C gives == higher precedence than &. That decision is widely agreed to be a mistake, and it is now permanent: flags & 1 == 1 means flags & (1 == 1), which is flags & 1 — nearly right, and quietly wrong for any other bit.

The same trap catches << versus +: 1 << n + 1 is 1 << (n + 1). Nothing warns you.

The rule that actually works in practice: when bitwise operators are mixed with anything else, use brackets. Reviewers stop asking, and you stop guessing.

Example

unsigned int flags = 8;   /* bit 3 set */
int wrong = flags & 8 == 8;   /* & (8 == 8) -> flags & 1 -> 0 */
int right = (flags & 8) == 8; /* -> 1 */

Both lines compile without a murmur. One of them is always wrong.

Before you run it

unsigned int flags = 4;   /* bit 2 set */
printf("%d\n", flags & 4 == 4);

What is printed?

Your task

Write int has_flag(unsigned int flags, unsigned int mask) that returns 1 when every bit in mask is set in flags, and 0 otherwise. Bracket it so it is right for any mask.

Stuck?

Explain it

Why compare against mask rather than against zero?

Not graded — this is for you.

Where this goes

Project 3 includes a precedence section for this reason. Anything you write there that mixes & or | with a comparison should be bracketed.