C: Unions and Enumerations

🗓 Last updated: 2026-11-30👤 Written by: Gray✓ Reviewed by: Alex🏷 Category: C Tutorial

A union is like a multi-purpose charging cable — you can only use one interface at a time, but it saves space. An enum is like a menu number — using names instead of raw numbers makes code more readable.

Reference entries in this section: union int float #define enum

1. union Definition and Shared Memory

All members of a union share the same memory. Its size equals the size of its largest member. Only one member can be used at a time.

C
// Struct/enum/union definition
union Data {
    // Variable declaration
    int i;
    // Variable declaration
    float f;
    char str[4];
};

// I/O operation
printf("%zu\n", sizeof(union Data));
TEXT
4

After assigning to the int member, reading the float member gives a different interpretation of the same memory:

C
union Data d;
d.i = 42;
// I/O operation
printf("i = %d\n", d.i);
// I/O operation
printf("f = %f\n", d.f);
TEXT
i = 42
f = 0.000000
⚠️ Note: Reading a member other than the one last written is implementation-defined (depends on platform and types). In practice, use a tag field to distinguish which member is currently valid.


2. union vs. struct

Feature struct union
Memory Each member has its own space All members share the same space
Size Sum of all member sizes (with alignment padding) Size of the largest member
Simultaneous access All members can be accessed at the same time Only one member at a time
Modification Changing one doesn't affect others Changing one affects all
C
// Struct/enum/union definition
struct SData {
    // Variable declaration
    int i;
    // Variable declaration
    float f;
    char str[4];
};

// Struct/enum/union definition
union UData {
    // Variable declaration
    int i;
    // Variable declaration
    float f;
    char str[4];
};

// I/O operation
printf("struct: %zu\n", sizeof(struct SData));
// I/O operation
printf("union:  %zu\n", sizeof(union UData));
TEXT
struct: 12
union:  4

3. Tagged Unions

In practice, unions are typically paired with a tag field that indicates which type is currently stored:

C
// Type definition
typedef struct {
    // Variable declaration
    int type;
    union {
        // Variable declaration
        int int_val;
        // Variable declaration
        float float_val;
        char str_val[32];
    } value;
} Variant;

// Function definition
void print_variant(const Variant *v) {
    // Switch statement
    switch (v->type) {
        // Case branch
        case 0: printf("int: %d\n", v->value.int_val); break;
        // Case branch
        case 1: printf("float: %f\n", v->value.float_val); break;
        // Case branch
        case 2: printf("str: %s\n", v->value.str_val); break;
    }
}

▶ Example

▶ Try it Yourself
TEXT
int: 42
double: 3.14

4. enum Definition and Usage

Enumerations use names instead of integer constants, improving code readability.

C
// Struct/enum/union definition
enum Color {
    RED,
    GREEN,
    BLUE
};

enum Color favorite = GREEN;
// Conditional check
if (favorite == GREEN) {
    // I/O operation
    printf("Green selected\n");
}
TEXT
Green selected

(1) Specifying Enum Values

C
// Struct/enum/union definition
enum Weekday {
    MON = 1,
    TUE,
    WED,
    THU,
    FRI,
    SAT = 100,
    SUN
};

// I/O operation
printf("MON=%d SAT=%d SUN=%d\n", MON, SAT, SUN);
TEXT
MON=1 SAT=100 SUN=101
💡 Tip: Enum constants without an explicit value automatically take the previous value + 1. The first defaults to 0.

(2) enum with switch

C
// Struct/enum/union definition
enum Direction { UP, DOWN, LEFT, RIGHT };

// Function definition
void move(enum Direction d) {
    // Switch statement
    switch (d) {
        // Case branch
        case UP:    printf("Move up\n"); break;
        // Case branch
        case DOWN:  printf("Move down\n"); break;
        // Case branch
        case LEFT:  printf("Move left\n"); break;
        // Case branch
        case RIGHT: printf("Move right\n"); break;
    }
}
⚠️ Note: Enums are backed by int — you can assign any integer value, and the compiler may not warn. Don't abuse this feature.


5. Underlying int Values of Enums

Enum constants are essentially named constants of type int.

C
// Struct/enum/union definition
enum Status { OK = 200, NOT_FOUND = 404, ERROR = 500 };
// I/O operation
printf("%d %d %d\n", OK, NOT_FOUND, ERROR);
TEXT
200 404 500

Enum variables can be assigned to and from integers (in C), but it's best to use enum values for type consistency:

C
enum Status s = OK;
// Variable declaration
int code = s;
💡 Tip: Prefer enums over #define for constants: enums have type information, display symbolic names in debuggers, and have more controllable scope.


6. Using union to Detect Endianness

Endianness refers to the byte order of multi-byte data in memory. A union makes it easy to detect:

C
// Function definition
int is_little_endian(void) {
    union {
        // Variable declaration
        int i;
        // Variable declaration
        char c;
    } u;
    u.i = 1;
    // Return result
    return u.c == 1;
}

If the lowest byte is stored at the lowest address (u.c == 1), it's little-endian; otherwise it's big-endian.

▶ Example

▶ Try it Yourself
TEXT
Memory byte order: 78 56 34 12
Little Endian
🔥 Common Mistake: x86/ARM are typically little-endian, while network transmission uses big-endian (network byte order). Understanding endianness is essential for protocol parsing and file format handling.


7. union for Memory Savings in Practice

When a struct has multiple mutually exclusive fields, use a union to save space:

C
// Type definition
typedef struct {
    // Variable declaration
    int type;
    union {
        struct { int width, height; } rect;
        struct { int radius; } circle;
        struct { int side; } square;
    } shape;
} Figure;

Figure f;
f.type = 1;
f.shape.circle.radius = 10;

Only one of the three shapes is used at a time. The union shares memory, and the struct size is determined by the largest shape.

▶ Example 3: Detecting Endianness with a Union

▶ Try it Yourself

输出(little-endian, e.g., x86):

TEXT
Byte order: 04 03 02 01
This is a little-endian system.

Reference entries in this section: union int float #define enum

❓ FAQ

Q What is enum type in C?
A An enum is a user-defined type that represents a set of named integer constants. By default values start at 0 and increment, but you can assign specific integers. Debuggers display enum names symbolically, making enums far more readable than #define magic numbers.
Q Can a union use multiple members at the same time?
A No. All union members share the same memory — writing one overwrites the others. You should only read the member that was last written. Reading a different member (type punning) is technically undefined behavior in C but widely used for low-level tricks like checking endianness.
Q What is a typedef enum in C?
A typedef enum { RED, GREEN, BLUE } Color; creates both an enum type named (anonymous in this case) and a typedef alias Color. After that you can write Color c = RED; without the enum keyword. This is why typedef is so common with both enums and structs.
Q How to convert enum to string in C?
A C has no built-in enum-to-string. You must write a mapping function or array of strings indexed by enum value. Many people use X-macros or _Generic (C11) for type-safe conversion. A good approach: declare const char *color_names[] = {"Red", "Green", "Blue"}; and index into it.
Q What is the difference between union and struct?
A A struct's members occupy separate memory — all are stored together. A union's members share the same memory — the total size equals the largest member. Use a struct when you need all fields simultaneously; use a union when you need one of several alternative representations of the same memory.
Q What is a tag field in a union?
A A tag field (or discriminator) is an enum stored alongside a union that indicates which union member is currently valid. Without it, there is no way for the compiler or runtime to know which member was last written. This combination is called a tagged union (or discriminated union) and is the standard safe way to use unions in C.
Q What is the difference between enum and #define for constants?
A enum has a concrete type (int), debuggers display symbolic names, and scope is scoped to the declaration (same scope as a typedef). #define is a preprocessor substitution with no type and no scope. Use enum for all but truly numeric compile-time constants — and even then, enum is usually better.

📖 Summary

📝 Exercises

  1. Define union IPAddress containing unsigned int addr and unsigned char bytes[4]. Input an IP integer value and output it as both an integer and four separate bytes
  2. Define an enum enum Season { SPRING, SUMMER, AUTUMN, WINTER } and write a function that returns the corresponding season name string based on the enum value
  3. Use a tagged union to implement a simple shape struct with a type tag and union (rectangle/circle), then write a function to calculate the area
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏