A bitwise flag system written in C, modelling the kind of status register you'd find in embedded and defence software.
Three flags are defined — READY, ARMED, FAULT — each mapped to a unique bit in a uint8_t status register. The program demonstrates setting a flag, checking it, and toggling it off.
Each flag is a power of 2, occupying a unique bit position:
#define READY (1 << 0) // 00000001
#define ARMED (1 << 1) // 00000010
#define FAULT (1 << 2) // 00000100| Function | Code | Effect |
|---|---|---|
| set_flag | status |= flag |
Forces bit ON |
| clear_flag | status &= ~flag |
Forces bit OFF |
| toggle_flag | status ^= flag |
Flips bit |
| check_flag | !!(status & flag) |
Returns 0 or 1 |
gcc -Wall -Wextra -Werror -std=c11 -pedantic -o bitwise_flags main.c
./bitwise_flagsReal hardware registers work exactly this way. For example, a UART status register might look like:
Bit 0 — TX ready
Bit 1 — RX data available
Bit 2 — Parity error
Bit 3 — Overflow
You read the register, mask off the bit you care about, and act on it. The patterns here — |=, &= ~, ^=, & flag — are used constantly in device drivers, interrupt handlers, and comms stacks.