site banner

Friday Fun Thread for January 31, 2025

Be advised: this thread is not for serious in-depth discussion of weighty topics (we have a link for that), this thread is not for anything Culture War related. This thread is for Fun. You got jokes? Share 'em. You got silly questions? Ask 'em.

2
Jump in the discussion.

No email address required.

I've worked in probably over a dozen codebases across 20 years and never once organically encountered anyone using a union.

I use (and organically run across) unions fairly frequently. That being said, embedded codebases are rather niche.

In embedded you're not typically concerned too much about portability between completely different architectures or compilers anyway, meaning you can (relatively) safely rely on things like "the compiler will be sane and predictable about its rules for padding bytes".

Main usecases are:

  • Describing hardware registers as both bits and an 'all' with a minimal of boilerplate and zero runtime cost. (Union of a bitfield describing the fields of the register with an e.g. u32)
  • Describing hardware registers that legitimately have multiple different interpretations depending on context. ("Isn't this just a tagged union?" Arguably yes, but crucially it is one where you do not have control over where the tag lives, or indeed if the tag exists in memory at all as opposed to being e.g. implicit in control flow.)
  • Manually-tagged tagged unions to save memory.
  • Task-based hardware accelerators with multiple task formats.
  • Manually-tagged tagged unions for user data in fixed-length tasks passed to hardware accelerators.
  • Working around braindead compiler pessimisations by emulating a C++-style bitcast in . (See above re: lack of portability.)