Interview Q&A · C · 12 questions in this topic
Structs, Unions, Enums & Typedef — C Interview Q&A
User-defined types — layout and padding, unions, bit-fields, enums and opaque-pointer encapsulation. Part of Structs, Unions & Enums · 202 questions in the C bank.
What is a struct and how do you declare, initialize and use one?
Answer
A struct groups heterogeneous members under one type. Declare with struct tags, initialize with brace lists or designated initializers (C99: .field = value, order-independent and self-documenting), access via . and ->.
Prefer typedef anonymous-struct or named-tag style per codebase convention, and initialize explicitly — padding bytes stay indeterminate otherwise.
Example
struct point { int x, y; }; struct point p = { .y = 2, .x = 1 }; /* designated: order-free */ struct point *q = &p; q->x = 9; /* arrow through pointer */
💡 Designated initializers are the modern style — they survive member reordering.
What is struct padding and alignment? How do you minimize it?
Answer
Members must sit at addresses that are multiples of their alignment, so the compiler inserts padding between members and at the end (for array strides). Order members by decreasing alignment (doubles/pointers, then ints, then shorts/chars) to shrink the struct; use static_assert on sizeof for wire formats.
#pragma pack / __attribute__((packed)) removes padding but risks unaligned access — memcpy fields out instead.
Example
/* padded (likely 12+ bytes): char, int, char */ /* struct bad { char a; int b; char c; }; */ /* packed-by-ordering: */ struct good { int b; char a; char c; };
💡 Sort members big-alignment-first is the one-line packing rule.
What is the difference between `struct A`, `typedef struct {} A`, and `struct A {}` usage?
Answer
struct A { ... }; declares a tag usable only as struct A. typedef struct { ... } A; creates alias A usable bare. typedef struct A { ... } A; gives both (needed for self-referential types like linked lists).
Self-referential structs must use the tag form inside (struct node *next) since the typedef name is not yet in scope.
Example
typedef struct node { int value; struct node *next; /* tag required for self-reference */ } node_t;
What is a union and when is it the right tool?
Answer
A union overlays all members at offset zero — size equals the largest member, and only one member is meaningful at a time. Right tools: memory-efficient alternatives with a tag enum (tagged union), protocol variants, and register views.
Always pair with a discriminant (tag) recording which member is live; reading a different member than written is implementation-defined/UB territory outside deliberate punning.
Example
typedef enum { IS_INT, IS_FLOAT } kind_t; typedef struct { kind_t kind; /* tag: which member is live */ union { int i; float f; } u; } value_t;
💡 Union without a tag is a bug waiting for a reader — the tag is the discipline.
What are bit-fields? What are their portability traps?
Answer
Bit-fields (unsigned x : 3) pack flags into shared storage with named widths — compact hardware/protocol mappings. Traps: layout and ordering are implementation-defined (no portable wire format), plain-int bit-field signedness varies, pointers to bit-fields are banned, and atomicity is absent.
Use them for memory-lean in-memory flags; use explicit masks and shifts for anything crossing a compiler, wire or file boundary.
Example
struct flags { unsigned ready : 1; unsigned error : 3; unsigned : 4; /* unnamed padding bits */ };
What is an enum and why is it better than #define constants?
Answer
Enums name related integer constants with scope, type identity and debugger visibility — traffic-light states read as RED/GREEN instead of 0/1. They beat macros with type checking and IDE support, and beat magic numbers with self-documentation.
Size the backing explicitly (enum : unsigned char in C23 / compiler attributes) for ABI stability, and always handle all enumerators in switches (default + -Wswitch).
Example
typedef enum { RED, GREEN, BLUE } color_t; /* switch (c) { case RED: ...; } // -Wswitch flags missing cases */
💡 Named states plus exhaustive-switch checking is the enum value proposition.
What is `typedef` really doing, and what are its pitfalls?
Answer
typedef creates type aliases — not new types. Aliases document intent (size_t, node_t), shrink complex declarators (function pointers), and centralize platform variance (int32_t). Pitfalls: hiding pointers (typedef char* str hides indirection and const subtleties), and over-abbreviating (single-letter soup).
Never hide * in typedefs for ownership-carrying types — visible stars keep free/delete pairing reviewable.
Example
typedef int *int_ptr; /* legal but discouraged: hides indirection */ typedef void (*handler_t)(int fd); /* good: tames function pointers */
How do opaque pointers give C encapsulation?
Answer
Declare struct sensor; in the header with no definition — clients can hold sensor* but cannot see members, compute sizeof, or forge instances. All access flows through API functions; the .c file holds the real definition.
This buys information hiding, ABI stability (members change without recompiling clients), and enforced invariants — the C answer to private members.
Example
/* sensor.h: typedef struct sensor sensor_t; // incomplete */ /* sensor_t *sensor_open(int id); void sensor_close(sensor_t *s); */ /* sensor.c holds: struct sensor { int fd; ... }; */
💡 Incomplete type in header, real definition in .c — the whole pattern in one sentence.
How are structs passed to and returned from functions?
Answer
Small structs may pass/return by value (copied — simple, but copies on every call). Large structs travel by const pointer (no copy, read-only promise). Returns by value are fine for small results; large results use caller-provided out-pointers.
Copy cost grows with sizeof, so measure: the by-value convenience has a per-call price the profiler can see.
Example
typedef struct { double x, y; } point_t; double dist(point_t a, point_t b); /* small: by value ok */ void transform(const point_t *in, point_t *out); /* large: pointers */
What is `offsetof` and `container_of`, and where are they used?
Answer
offsetof(type, member) (from <stddef.h>) gives the member byte offset — the portable way to do serialization math and static_assert layouts. container_of (Linux kernel macro) recovers the enclosing struct address from a member pointer via offset subtraction — the backbone of intrusive lists.
Intrusive structures (list node embedded in the object, zero extra allocations) power kernels and embedded systems where malloc-per-node is unaffordable.
Example
#include <stddef.h> /* size_t off = offsetof(struct packet, len); // portable offset */ /* container_of(ptr, struct item, link) // enclosing object */
💡 offsetof for layout math, container_of for intrusive structures — the kernel-programmer duo.
What is the difference between deep copy and shallow copy of structs?
Answer
Shallow copy duplicates the struct bytes (assignment, memcpy) — pointer members end up shared, so double-free or action-at-a-distance follows. Deep copy duplicates pointees too — independent lifetimes at allocation cost.
Structs owning pointers need explicit copy/clone/destroy functions (the C analog of copy constructors) documenting which convention each API uses.
Example
typedef struct { char *name; } user_t; /* user_t b = a; // shallow: b.name aliases a.name (danger!) */ /* deep: b.name = strdup(a.name); // independent, must free */
How do you compare and hash structs (for sorting, dedup, tables)?
Answer
Never memcmp whole structs (padding bytes are indeterminate — equal values can compare unequal). Compare member-by-member, or canonicalize (memset the struct zero first, then compare). Hash likewise over defined members only.
qsort/bsearch comparators must implement strict ordering over the key members and never read padding.
Example
/* WRONG: memcmp(&a, &b, sizeof a) // padding indeterminate */ /* RIGHT: compare .id, then .name with strcmp, ... */
Recommended resourcesAffiliate links · may earn us a commission