String + Length: A Zero-Overhead Trick in C
In C you often need to keep a string together with its length. Calling strlen() every time means extra memory scans. We want it compact and…
String + Length: A Zero-Overhead Trick in C
In C you often need to keep a string together with its length. Calling strlen() every time means extra memory scans. We want it compact and efficient.
✅ Solution
A tiny trick with typedef + macro:
typedef struct { const char *p; size_t n; } sv;
#define SV(s) { (s), sizeof(s) - 1 }
struct Messages {
sv error, version, rep_prefix;
};
static const struct Messages mess = {
SV("error"),
SV("version"),
SV("Server reply: ")
};
After preprocessing it becomes:
static const struct Messages mess = {
{ ("error"), sizeof("error") - 1 },
{ ("version"), sizeof("version") - 1 },
{ ("Server reply: "), sizeof("Server reply: ") - 1 }
};
— string and its length, no redundant strlen().
Usage
#include <stdio.h>
int main(void) {
fwrite(mess.rep_prefix.p, 1, mess.rep_prefix.n, stdout);
fwrite("OK\n", 1, 3, stdout);
return 0;
}
Handy in network protocols, logging, binary formats — string + size always at hand, zero overhead.

메타데이터
- post_id
- feff1c557eee
- slug
- string-length-a-zero-overhead-trick-in-c-feff1c557eee
- url
- https://medium.com/@anton_ds/string-length-a-zero-overhead-trick-in-c-feff1c557eee
- canonical_url
- https://medium.com/@anton_ds/string-length-a-zero-overhead-trick-in-c-feff1c557eee
- author_url
- https://medium.com/@anton_ds
- status
- ok
- fetched_at
- 2026-06-24 16:30:55