I have the following code:
struct StudentStruct {
char name[32];
float score;
};
and it is initialized this way:
StudentStruct students[1000];
for (size_t i = 1; i < sizeof(students) / sizeof(students[0]) - 5; ++i) {
Ops[i] = (StudentStruct){"Empty", 0.0};
}
students[ 0] = (StudentStruct){"Alex", 78.9};
// There will always be a huge gap, which could prevent some
// possible syntax to work
students[995] = (StudentStruct){"Bob", 3.14};
students[996] = (StudentStruct){"Charlie", 2.71};
students[997] = (StudentStruct){"David", 99.9};
students[998] = (StudentStruct){"Eugene", 0 };
students[999] = (StudentStruct){"Frank", -2.2};
// This is just an example, in reality I would need to manually define hundreds of them.
This works well until I enabled -Wpedantic
which complains that warning: ISO C++ forbids compound-literals [-Wpedantic]
. I am wondering if there is a ISO C++-compliant way that does something very similar.
I am aware of the following:
- brace initialization: but after playing for a while it seems to me that it can't fit into my case.
- change
struct
toclass
and prepare a constructor: this should work, but I would prefer keepingstruct
if possible because the code may potentially be called in other languages, have a simple memory layout makes me feel a little bit better.
Any idea?
EDIT:
- Some answers point to this:
students[0] = { "Alex", 78.9 };
I am not sure why, it doesn't work with my g++, the error is:
error: no match for ‘operator=’ (operand types are ‘StudentStruct’ and ‘<brace-enclosed initializer list>’)
- I am using
g++ 10.2.1
and using the method in this post, the default C++ standard is C++14.