3 ms·
You can already do struct bla_t { int a; const char* hello; } blub = { .a = 23, .hello = "Hello World!", };
by pantalaimon 4y ago
You can already do
struct bla_t {
int a;
const char* hello;
} blub = {
.a = 23,
.hello = "Hello World!",
};
- flohofwoe 4y agoNo that's just creating an item 'blub' of struct 'bla_t', it doesn't help with default values that the compiler could fill in with when using designated init instead of zeroes. To borrow from your example: struct bla_t { int a = 23; const char* hello = "Hello World!"; } blub = { .a = 46, }; The missing designated init item blub.hello would now be initialized to "Hello World!" by the compiler by looking up the default value in the struct declaration. Currently, missing designated init items are set to zero. And it would work in any other place where a bla_t is created: struct bla_t blob = {}; This would initialize blob to its default state of blob.a = 23 and blob.hello = "Hello World!".
- pantalaimon 4y agoBut this is the exact kind of implicit magic I’m happy that C does not have. If I look at a piece of code that does struct bla_t blub = { .a = 46, }; I know that everything except .a will be zero, without knowing anything about bla_t. With your proposal I would now get a 'helpful' default that might not be what I want at all.
- flohofwoe 4y agoThat's a fair point of course, but when you pass 'blub' into a library function, this function needs to fill in the zeroes with default values anyway, and that's just as opaque, and it causes extra runtime overhead which wouldn't be there if the compiler already knows the default values.
- pantalaimon 4y ago> this function needs to fill in the zeroes with default values anyway Wait - no. What's wrong with #define BLA_INIT_DEFAULT { .a = 23, .hello = "Hello World!", } struct bla_t blub = BLA_INIT_DEFAULT; blub.a = 42; That's what your proposal would do under the hood anyway, just more explicit.
- flohofwoe 4y agoYou can even change that to: #define BLA_DEFAULTS .a = 23, .hello = "Hello World!" struct bla_t blub = { BLA_DEFAULTS, .a = 42, }; ...because C99 allows designated initializers to show up multiple times, but that's all a bit too much macro magic for my taste, I'd really prefer the defaults in the struct declaration.