π Problem
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.
Top comments (0)