c / intermediate
Snippet
Encapsulation with Opaque Pointers
Opaque pointers allow you to hide the internal implementation of a structure from the user. By only providing a forward declaration in the header file and defining the struct in the C file, you achieve encapsulation similar to private members in OOP.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// point.htypedef struct Point Point;Point* create_point(int x, int y);void print_point(Point* p);// point.c#include <stdio.h>#include <stdlib.h>struct Point {int x, y;};Point* create_point(int x, int y) {Point* p = malloc(sizeof(struct Point));if (p) { p->x = x; p->y = y; }return p;}void print_point(Point* p) {printf("Point: %d, %d\n", p->x, p->y);}
Breakdown
1
typedef struct Point Point;
Forward declaration that tells the compiler 'Point' exists without revealing its fields.
2
struct Point { int x, y; };
The actual definition is hidden in the .c file, preventing direct access to x and y from outside.