c / expert
Snippet
Discriminated Tagged Union Expressions with Pattern Matching Dispatch
Demonstrates type-safe variant types (tagged unions/sum types) in standard C. An enum discriminator tag guards active union field access during recursive control flow traversal of abstract syntax tree nodes.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>typedef enum { NODE_INT, NODE_ADD } NodeType;struct Node;typedef struct {struct Node* left;struct Node* right;} BinaryOp;typedef struct Node {NodeType type;union {int value;BinaryOp op;} as;} Node;int eval_node(const Node* node) {switch (node->type) {case NODE_INT:return node->as.value;case NODE_ADD:return eval_node(node->as.op.left) + eval_node(node->as.op.right);}return 0;}
Breakdown
1
typedef enum { NODE_INT, NODE_ADD } NodeType;
Defines explicit variant type tags used to identify which union field contains valid data.
2
union { int value; BinaryOp op; } as;
Declares an un-padded overlapping memory layout structure for storing mutually exclusive variant payloads.
3
switch (node->type)
Executes dynamic pattern matching dispatch based on the structural discriminator tag.