0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
C · ExpertSnippet

Strict Aliasing and the restrict Keyword

Strict aliasing allows the compiler to assume that pointers of different types do not alias the same memory. The 'restrict' qualifier (C99) explicitly informs the compiler that for the lifetime of the pointer, only it (and pointers derived from it) will be used to access the object it points to. This enables aggressive optimizations, such as loading values into registers once instead of re-fetching them from memory due to potential side effects.

snippet.c
c
1
2
3
4
5
6
void vector_add(int * restrict a, int * restrict b, const int * restrict src, int n) {
for (int i = 0; i < n; i++) {
a[i] += src[i];
b[i] += src[i];
}
}
PerformanceBest Practices
C · ExpertSnippet

Flexible Array Members (C99)

A flexible array member is an unsized array declaration at the end of a struct. It allows for a single contiguous memory allocation for both the metadata (header) and the payload (data). This avoids double-pointer indirection, simplifies memory management, and significantly improves cache locality compared to a pointer to a separate heap allocation.

snippet.c
c
1
2
3
4
5
6
7
8
struct Packet {
int header_id;
size_t length;
unsigned char data[]; // Flexible array member
};
struct Packet *p = malloc(sizeof(struct Packet) + 1024);
p->length = 1024;
Arrays & ListsMemory Management
C · ExpertSnippet

Volatile and Signal Safety

The 'volatile' qualifier prevents the compiler from caching a variable's value in a register, forcing it to read from memory every time. 'sig_atomic_t' is a type that can be accessed as an atomic entity even in the presence of asynchronous interrupts. Together, they are essential for variables shared between the main execution thread and signal handlers to prevent infinite loops or race conditions.

snippet.c
c
1
2
3
4
5
6
7
8
9
#include <signal.h>
volatile sig_atomic_t keep_running = 1;
void handle_sigint(int sig) {
keep_running = 0;
}
// In main: while(keep_running) { /* loop */ }
SyntaxMemory Management
C · ExpertSnippet

Encapsulation with Opaque Pointers (ADTs)

Opaque pointers (often called 'handles' or the PIMPL idiom) allow for complete data encapsulation in C. By only providing a forward declaration in the header and defining the structure in the source file, clients cannot access internal fields directly. This improves binary compatibility (ABI) because the structure's layout can change without requiring clients to recompile.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
// In header (public interface)
typedef struct connection_s* connection_t;
connection_t conn_create(const char *url);
void conn_send(connection_t c, const char *msg);
// In source (implementation details hidden)
struct connection_s {
int socket_fd;
char buffer[1024];
bool is_encrypted;
};
FunctionsBest Practices
C · ExpertSnippet

X-Macros for Synchronized Definitions

The X-Macro pattern is a powerful preprocessor technique used to maintain multiple related lists (like enums, strings, or switch cases) in sync. You define a list once and then 'apply' it by redefining the 'X' macro before each use. This prevents errors where an enum is updated but the corresponding string array is forgotten.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define STATUS_LIST \
X(IDLE, "System is waiting") \
X(BUSY, "Processing task") \
X(ERROR, "Fault detected")
// Generate Enum
typedef enum {
#define X(a, b) STATUS_##a,
STATUS_LIST
#undef X
} status_t;
// Generate String Table
const char* status_msg[] = {
#define X(a, b) b,
STATUS_LIST
#undef X
};
SyntaxBest Practices
C · ExpertSnippet

Atomic Compare-and-Swap (CAS) with stdatomic.h

Uses C11's stdatomic.h to perform a lock-free update. atomic_compare_exchange_weak checks if the current value matches 'expected'; if so, it updates it to 'desired'. If not, it updates 'expected' with the actual current value, allowing for a retry loop.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
#include <stdatomic.h>
#include <stdbool.h>
void safe_update(atomic_int *val) {
int expected = atomic_load(val);
int desired;
do {
desired = expected + 1;
} while (!atomic_compare_exchange_weak(val, &expected, desired));
}
Memory ManagementPerformance
C · ExpertSnippet

C99 Compound Literals for Temporary Objects

Compound literals allow creating unnamed objects on the fly. They are lvalues, meaning you can even take their address. This is extremely useful for passing complex arguments to functions without cluttering the scope with temporary variables.

snippet.c
c
1
2
3
4
5
6
7
8
typedef struct { int r, g, b; } Color;
void apply_color(Color c);
int main() {
// Passing an anonymous struct object without a variable
apply_color((Color){255, 128, 0});
return 0;
}
SyntaxMemory Management
C · ExpertSnippet

Variadic Macros with __VA_ARGS__

The __VA_ARGS__ identifier is used in the macro expansion to represent the variable arguments passed to the macro. This allows creating powerful wrappers around functions like printf while automatically injecting metadata like file names and line numbers.

snippet.c
c
1
2
3
4
5
6
7
8
9
#include <stdio.h>
#define DEBUG_LOG(fmt, ...) \
fprintf(stderr, "[DEBUG] %s:%d: " fmt "\n", __FILE__, __LINE__, __VA_ARGS__)
int main() {
DEBUG_LOG("Processing %d items", 42);
return 0;
}
SyntaxFunctions