Skip to content
Learn Netverks

Lesson

Step 18/36 50% through track

unions-bitfields

Unions and bit-fields

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Unions and bit-fields: the syntax, patterns, and safety habits you need before advancing in C.

Structs model data in kernels and embedded firmware—layout and alignment matter in production.

You will apply Unions and bit-fields in contexts like: Hardware registers, protocol packing, and checksum implementations.

Write C in main.c with int main(), click Run on server—the dev runner compiles with cc/gcc -std=c11 and runs the binary; read stderr for compile and linker errors (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

A union shares one memory region among multiple members—only one member is active at a time. Bit-fields pack small integers into struct bits, common in hardware registers.

Union example

union Value {
    int i;
    float f;
};
union Value v;
v.i = 42;   /* active member is i */

Reading a different member than was last written is allowed in C but the value may be implementation-defined unless using common initial sequences carefully.

Bit-fields

struct Flags {
    unsigned int ready : 1;
    unsigned int mode  : 3;
};

Important interview questions and answers

  1. Q: Union vs struct?
    A: Struct lays out all members; union overlaps them—size is the largest member.
  2. Q: When use unions?
    A: Type punning for protocols, variant payloads, or embedded register views—with care for strict aliasing rules.

Self-check

  1. How many bytes does a union allocate?
  2. What are bit-fields often used for?

Interview prep

Union vs struct?

Struct lays out all members sequentially; union members overlap—size equals largest member.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Union type punning?
  • Bitfield portable?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump