Closed alexey-utkin closed 2 years ago
For the common case we have several limitations.
Example 1:
struct MyStruct {
short x;
const int a; // <-- const !
};
struct MyStruct st = {0, 1}; // OK
struct MyStruct st; // error: call to implicitly-deleted default constructor of 'struct MyStruct'
st.x = 0;
st.a = 1; // impossible
Example 2:
struct One {
int a;
char str[12];
};
struct One expected;
expected.a = 1;
char __expected_str[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'}; // two lines initialization
memcpy((void *) expected.str, __expected_str, sizeof(__expected_str)); // looks not good
It seems that line-by-line initialization with field name could be a better solution:
struct MyStruct {
short x;
const int a;// <-- const !
};
struct MyStruct st = {
.x = 0,
.a = 1};
struct One {
int a;
char str[12];
};
struct One expected = {
.a = 1,
.str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'}};
struct MyStructWithOne {
short x;
const int a;// <-- const !
struct One one;
};
struct MyStructWithOne ex = {
.x = 2,
.a = 1,
.one = {
.a = 1,
.str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'}}};
Additional info: Struct and union initialization
It seems a good way! And seems the only condition to support this is the compiler at least support C99?
@llmagic That is right. C99 or Cpp98 are required.
But it should not be a problem to comment the designation
if a custom compiler does not support the option.
Fixed in PR
We need the option to transform initialization from initialization-list-based way
to struct-field-based:
Seems like it should be a UI option in the formatting settings.