Skip to content
C Basics: Update Independent Options with Unsigned Bit Masks

C Basics: Update Independent Options with Unsigned Bit Masks

November 1, 2026

A small unsigned integer can hold independent options. Give each option one bit and distinguish “at least one requested option” from “every requested option.”

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install GCC and the C standard-library development headers, and make gcc available on PATH. You also need Bash, a text editor, and mktemp, rm, and rmdir. No third-party C library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as unsigned-bit-flags-demo.c:

#include <stdio.h>

int main(void)
{
    const unsigned int read_flag = 1u << 0;
    const unsigned int write_flag = 1u << 1;
    const unsigned int trace_flag = 1u << 2;
    unsigned int options = read_flag | trace_flag;
    const unsigned int requested = read_flag | write_flag;

    printf("Initial: %u\n", options);
    printf("Any requested: %s\n", (options & requested) != 0u ? "yes" : "no");
    printf("All requested: %s\n", (options & requested) == requested ? "yes" : "no");
    options |= write_flag;
    options &= ~trace_flag;
    printf("After set and clear: %u\n", options);
    options ^= write_flag;
    printf("After toggle: %u\n", options);
    return 0;
}

Compile and run it. The && prevents execution if compilation fails:

gcc -std=c17 -Wall -Wextra -Werror -pedantic unsigned-bit-flags-demo.c -o unsigned-bit-flags-demo &&
./unsigned-bit-flags-demo

Observed output:

Initial: 5
Any requested: yes
All requested: no
After set and clear: 3
After toggle: 1

Read the result

OR sets a bit, AND with the complemented mask clears it, and XOR toggles it. The any-bit check compares the intersection with zero; the all-bit check compares it with the entire requested mask.

Apply it carefully

Use unsigned operands and keep shift counts below the width of the promoted left operand. Do not replace bitwise operators with logical && or ||. A zero requested mask makes the all-bit test true; decide whether that is meaningful for your API. These local flags are not operating-system permissions or atomic shared state.

The GNU reference documents the relevant interface or language rules.

Clean up

Remove only the source and executable created here, then remove the empty practice directory:

rm -- unsigned-bit-flags-demo.c unsigned-bit-flags-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on