4 ms·
Declaring, instancing and initializing a global state struct in one go: static struct { int a; float b; const char* c; stru
by flohofwoe 6y ago
Declaring, instancing and initializing a global state struct in one go:
static struct {
int a;
float b;
const char* c;
struct {
float x, y, z;
} nested;
} state = {
.a = 1,
.b = 2.0f,
.c = "Hello World!",
.nested = {
.x = 1.0f, .z = 3.0f
},
};
Careful if the the struct contains big arrays though, this will let the executable size explode because a copy of the struct content is placed in the executable.
- nwellnhof 6y agoArrays of anonymous structs are also useful for non-global data: static struct { const char *key; const char *value; } elems[] = { { "k1", "v1" }, { "k2", "v2" }, { "k3", "v3" } }; for (int i=0; i<sizeof(elems)/sizeof(*elems); i++) { printf("%s => %s\n", elems[i].key, elems[i].value); }