basics · beginner · ~15 min

Set a bit

Force a single bit to 1.

Challenge

Implement:

unsigned set_bit(unsigned x, int i);

Return x with bit i set to 1 (idempotent). i is in 0..31.

Input format

x and a bit index i.

Output format

x with bit i = 1.

Constraints

i in 0..31.

Starter code

#include <stddef.h>
/* Return x with bit i set to 1. i in 0..31. */
unsigned set_bit(unsigned x,int i){ (void)i; return x; }

Common mistakes

Toggling instead of setting (breaks when the bit was already 1).

Edge cases to handle

Setting an already-set bit is a no-op.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.