basics · beginner · ~15 min

Toggle a bit

Flip a single bit with XOR.

Challenge

Implement:

unsigned toggle_bit(unsigned x, int i);

Return x with bit i flipped. i is in 0..31.

Input format

x and a bit index i.

Output format

x with bit i inverted.

Constraints

i in 0..31.

Starter code

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

Common mistakes

Using | (set) or & ~ (clear) instead of ^ (flip).

Edge cases to handle

Toggling twice restores the original value.

Background lessons

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