C Structures vs Unions

Intermediate
6 min read
Updated: Nov 2026
1 example

What Is Structures vs Unions?

A struct stores all members side by side, so its size is at least the sum of its members (plus padding) and every member is valid at once. A union stores all members in the same place, so its size is the largest member and only one is valid. Choose a struct for "this and that" data, a union for "this or that".

Remember
struct S { int a; double b; char c; };   /* a AND b AND c */
union  U { int a; double b; char c; };   /* a OR  b OR  c */

Cheat Sheet

Keep these facts handy while you work with Structures vs Unions in C.

TopicDetail
Memorystruct: sum plus padding; union: max
Active membersstruct: all; union: one
Initializationunion: first member by default
Typical usestruct: records; union: variants

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Enumerations.

Example 1 — Same members, different sizes

Sizes shown are typical for a 64-bit platform.

C
#include <stdio.h>

struct S { int a; double b; char c; };
union  U { int a; double b; char c; };

int main(void) {
    printf("struct S: %zu bytes\n", sizeof(struct S));
    printf("union  U: %zu bytes\n", sizeof(union U));

    union U u;
    u.a = 7;
    printf("u.a = %d\n", u.a);
    return 0;
}

How It Works

  1. The struct holds 4 + (4 padding) + 8 + 1 + (7 padding) = 24 bytes.
  2. The union only needs room for its largest member, 8 bytes.
  3. Writing u.a makes a the active member.

Edge Cases & Pitfalls

Check these before relying on Structures vs Unions in real programs.

assume

Assuming sizes

Sizes vary by platform and compiler. Always use sizeof.

mix

Using union fields at once

Setting u.a then u.b overwrites u.a.

Key Takeaways

  • struct: AND.
  • union: OR.
  • sizeof: verify, never assume.

One line: A struct stores all members side by side, so its size is at least the sum of its members (plus padding) and every member is valid at once.

Frequently Asked Questions

A union, because its members overlap. It is only suitable when members are never needed simultaneously.
Yes. This is the usual way to build a tagged union (variant) type.
Continue with "C Enumerations" next. Give names to related integer constants with enum. The C Structures, Unions and Enums hub lists every topic in order.

Next: Enumerations

Give names to related integer constants with enum.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful