Interview Q&A · C · 12 questions in this topic

Structs, Unions, Enums & Typedef — C Interview Q&A

All C topics

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

Example.cc
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

Example.cc
/* 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

Example.cc
typedef struct node {
    int value;
    struct node *next; /* tag required for self-reference */
} node_t;

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits