On this page
Structs, Unions & Enums
Prev: Arrays & C Strings | Up: fundamentals | Next: pointers_and_memory
Rel: Memory Layout, Alignment & Qualifiers, Type Systems
Ref: cppreference — Struct
Tags: #public #prog #c #fundamentals #structs
Contents
Structs, Designated Initializers & Padding
C compilers insert padding bytes between struct fields so each field sits at its natural alignment boundary. Order fields from largest alignment to smallest to minimize wasted space, and use C99 designated initializers (unspecified fields are zero-initialized):
#include <stdint.h>
typedef struct {
double x;
double y;
uint32_t id;
} Point;
Point p = { .x = 3.0, .y = 4.0, .id = 1 };
Tagged Unions (Sum Types in C)
A union overlays all members at the same memory address (size = largest member). Pair an enum tag with a union to build a safe discriminated union:
typedef enum { VAL_INT, VAL_DOUBLE } ValueKind;
typedef struct {
ValueKind kind;
union {
int64_t i;
double d;
} as;
} Value;
Linked from
Related notes
- tuts/c/fundamentals Linked here; links to this page; shared tags: #c, #fundamentals, #prog
- tuts/c/fundamentals/arrays_and_strings Linked here; links to this page; shared tags: #c, #fundamentals, #prog
- tuts/c/compilation_and_internals/memory_layout_and_abi Linked here; links to this page; shared tags: #c, #prog
- tuts/c/pointers_and_memory Linked here; shared tags: #c, #prog
- tuts/programming/data_and_types/type_systems Linked here; shared tags: #prog
- tuts/c/fundamentals/control_flow_and_functions shared tags: #c, #fundamentals, #prog
- tuts/c/fundamentals/syntax_types_and_operators shared tags: #c, #fundamentals, #prog
- tuts/c shared tags: #c, #prog
- tuts/c/builtins shared tags: #c, #prog
- tuts/c/builtins/__FILE__ shared tags: #c, #prog