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:
| Parameter | Type | Description |
|---|---|---|
| enum | Enumeration | Assigns sequential integer values to named symbols. |
| union | Data Structure | Shares single memory block across multiple member types. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C Structs: Grouping Heterogeneous Data Records
Define compound records in C using struct and typedef struct.
C Arrays: Contiguous Stack Buffers and Multi-Dimensional Arrays
Learn fixed-size arrays, memory layouts, indexing, and calculating element counts.
C Primitive Data Types and Explicit Format Specifiers
Master C primitive types (int, float, double, char, unsigned long), sizeof memory allocation, and explicit printf format specifiers.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.