How to initialize an array of structures without using compound literals but still in one line in C++


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:

  1. brace initialization: but after playing for a while it seems to me that it can’t fit into my case.
  2. change struct to class and prepare a constructor: this should work, but I would prefer keeping struct 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?

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>’)

>Solution :

Just remove the parens around the type name. Why would you need it?

students[  0] = StudentStruct{"Alex",    78.9};

Or you can remove the type name completely in this context:

students[  0] = {"Alex",    78.9};

Leave a Reply Cancel reply