HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

C++ Structure Initialization

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
structureinitializationstackoverflow

Problem

Is it possible to initialize structs in C++ as indicated below:

struct address {
    int street_no;
    char *street_name;
    char *city;
    char *prov;
    char *postal_code;
};

address temp_address = { .city = "Hamilton", .prov = "Ontario" };


The links here and here mention that it is possible to use this style only in C. If so why is this not possible in C++? Is there any underlying technical reason why it is not implemented in C++, or is it bad practice to use this style. I like using this way of initializing because my struct is big and this style gives me clear readability of what value is assigned to which member.

Please share with me if there are other ways through which we can achieve the same readability.

I have referred the following links before posting this question:

  • C/C++ for AIX



  • C Structure Initialization with Variable



  • Static structure initialization with tags in C++



  • C++11 Proper Structure Initialization

Solution

If you want to make it clear what each initializer value is, just split it up on multiple lines, with a comment on each:

address temp_addres = {
  0,  // street_no
  nullptr,  // street_name
  "Hamilton",  // city
  "Ontario",  // prov
  nullptr,  // postal_code
};

Code Snippets

address temp_addres = {
  0,  // street_no
  nullptr,  // street_name
  "Hamilton",  // city
  "Ontario",  // prov
  nullptr,  // postal_code
};

Context

Stack Overflow Q#11516657, score: 244

Revisions (0)

No revisions yet.