guybrush_threepwood
guybrush_threepwood

Reputation: 55

Initialize struct of struct using the member struct default values

I want to initialize a large struct containing other structs to a defined default value, similar to this question: Initialize a struct with struct types inside

However, in my real case, the struct contains many members, so defining the default value in the suggested way quickly becomes unreadable. Many of my members are of the same type, so I would like to do define a default value for those and use when defining the default value for the larger struct. Example:

struct name{
   char *firstName;
   char *lastName;
} name;

struct address{
   char *street;
   int number;
} address;

struct person{
   struct name fullName;
   struct address fullAddress;
   int age;
} person;

struct name default_name = {.firstName = "John", .lastName = "Doe"};
struct address default_address = {.street = "Street", .number = 42};

struct person default_person = {.fullName = default_name, .fullAddress = default_address, .age = 18};

The compiler complains at the last line that the default value is not a compile-time constant. How can I define default_person using default_name and default_address in a way the compiler understands?

EDIT: Example of what the real case looks more like to show the unreadability issue:

struct person default_person = 
{
  .fullName    = (struct name){ .firstName = "John", .lastName = "Doe" },
  .fullName    = (struct name){ .firstName = "John", .lastName = "Doe" },
  .fullName    = (struct name){ .firstName = "John", .lastName = "Doe" },
...
  .fullAddress = (struct address){ .street = "Street", .number = 42 },
  .fullAddress = (struct address){ .street = "Street", .number = 42 },
...
};

Upvotes: 1

Views: 609

Answers (1)

Lundin
Lundin

Reputation: 213276

If you place the struct variable declarations outside any function - at file scope - then the initializers must be compile-time constants (because such variables have static storage duration).

The easiest solution is to move the struct variables inside a function, because they probably shouldn't be at file scope anyway:

int main (void)
{
  struct name ...
}

If you need to have the declarations at file scope, you should look into merging them into a single variable with a single initializer list and it will work as well:

struct person default_person = 
{
  .fullName    = (struct name){ .firstName = "John", .lastName = "Doe" },
  .fullAddress = (struct address){ .street = "Street", .number = 42 },
};

Upvotes: 1

Related Questions