Home > Enterprise >  In C , how do I create a constexpr aggregate initialization for a struct that has an array of struc
In C , how do I create a constexpr aggregate initialization for a struct that has an array of struc

Time:02-02

I am working in C and I want to create an initializer list for a struct of array of structs and I keep getting the same compilation error.

Here is my struct:

typedef struct SetpointChange
{
    uint8_t hours;
    uint8_t minutes;
} SetpointChangeTime_t;

typedef struct SetpointChangesDaySchedule
{
    SetpointChangeTime_t dayChanges[4];
} SetpointChangesDaySchedule_t;

typedef struct SetpointChangesWeekSchedule
{
    SetpointChangeTime_t weekChanges[2];
} SetpointChangesWeekSchedule_t;

Here is my initializer list:

static constexpr SetpointChangesWeekSchedule defaultSchedule = {
   {
   {0,  0},
   {0,  0},
   {0,  0},
   {0,  0}
   },
   {
   {0,  0},
   {0,  0},
   {0,  0},
   {0,  0}
   }
};

I am getting this error:

error: too many initializers for 'SetpointProgram::SetpointChange_t [2]' {aka 'SetpointProgram::SetpointChange [2]'}
   75 | };
      | ^

My initialization syntax seems to be very correct... I don't understand why I am getting this error.

CodePudding user response:

This is aggregate initialization, not initializer list. You need to double braces in some places:

#include <cstdint>

typedef struct SetpointChange
{
    uint8_t hours;
    uint8_t minutes;
} SetpointChangeTime_t;

typedef struct SetpointChangesDaySchedule
{
    SetpointChangeTime_t dayChanges[4];
} SetpointChangesDaySchedule_t;

typedef struct SetpointChangesWeekSchedule
{
    SetpointChangesDaySchedule_t weekChanges[2];
} SetpointChangesWeekSchedule_t;

static constexpr SetpointChangesWeekSchedule defaultSchedule = {{
   {{
   {0,  0},
   {0,  0},
   {0,  0},
   {0,  0}
   }},
   {{
   {0,  0},
   {0,  0},
   {0,  0},
   {0,  0}
   }}
}};

Explanation is: first braces are for object, second are for array inside object.

Compiler allows to use single set, like this:

struct Test
{
    int a[5];
};

Test t = {1, 2, 3, 4, 5};

But in your case it will look like:

static constexpr SetpointChangesWeekSchedule defaultSchedule = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

Which is probably too confusing.

  • Related