C:C Enums and Unions: Memory Sharing and Named Constants
C•Enums & Unions

C Enums and Unions: Memory Sharing and Named Constants

Enums assign human-readable names to integers. Unions store different data types in the exact same memory space.

Syntax

enum Status { OK, WARN, ERR }; union Data { int i; float f; };

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
enumEnumerationAssigns sequential integer values to named symbols.
unionData StructureShares single memory block across multiple member types.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

#include <stdio.h>

typedef enum {
    STATUS_HEALTHY = 0,
    STATUS_DEGRADED = 1,
    STATUS_CRITICAL = 2
} SystemHealth;

typedef union {
    int intVal;
    float floatVal;
} SensorPayload;

int main(void) {
    SystemHealth health = STATUS_HEALTHY;
    printf("Enum Health Value: %d (STATUS_HEALTHY)\n", health);

    SensorPayload payload;
    payload.intVal = 42;
    printf("Union read as int:   %d\n", payload.intVal);

    payload.floatVal = 3.1415f;
    printf("Union read as float: %.4f\n", payload.floatVal);
    printf("Union total size:    %zu bytes (shares largest member)\n", sizeof(payload));

    return 0;
}
Expected Output:
Enum Health Value: 0 (STATUS_HEALTHY)
Union read as int:   42
Union read as float: 3.1415
Union total size:    4 bytes (shares largest member)

How It Works: Step-by-Step

  • Lines 3-7: Defines enum mapping system states to integer constants.
  • Lines 9-12: Defines union sharing 4 bytes of memory between int and float.

Key Concepts

  • Enums improve code readability and compile-time type safety over raw integers.
  • A union is only as large as its largest member (in this case 4 bytes).
  • Writing to one union member overwrites the value of all other members in the union.

Common Mistake: Reading from a union member other than the one most recently written

Reading payload.intVal after writing to payload.floatVal reinterprets raw IEEE float bytes as an int.

❌ Incorrect
payload.floatVal = 3.14f;
printf("%d", payload.intVal); // Prints raw float bit-pattern as integer!
✅ Correct
// Only read the active union member currently stored

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler