3

AFAIK, "designated initialization" is a C++20 feature(ref: https://en.cppreference.com/w/cpp/language/aggregate_initialization).

However, the following code,

// main.cc
#include <iostream>

struct Person
{
  const char *name;
  int age;
};

int main(int argc, char *argv[])
{
  Person person = {
      .name = "Bob",
      .age = 24,
  };
  std::cout << person.name << "\n"
            << person.age << "\n";
  return 0;
}

compiles with the the command g++ -Wall -Werror -std=c++11 -o main main.cc (also std=c++17).

Why is this so?

My g++ --version:

g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Hakkyu Kim
  • 43
  • 3
  • 2
    If you don't want to use gcc extensions, add `-pedantic` to your compiler options. (I'll see if there is a duplicate somewhere.) – JaMiT Nov 24 '21 at 00:26
  • 1
    The feature was added in C a long time ago and was used as a C++ extension prior to C++20. – Eugene Nov 24 '21 at 00:30
  • I didn't find something I'd call a duplicate, but there are related posts: [Why was `identifier : expression` form of designated initialization deprecated/obsoleted in GCC?](https://stackoverflow.com/questions/68750388/) and [Why are designated initializers not implemented in g++](https://stackoverflow.com/questions/4900739/), with [this answer](https://stackoverflow.com/a/55434499) of particular note. – JaMiT Nov 24 '21 at 00:37
  • 1
    Because some compilers allow invalid C++ but valid C as extentions. VLA is a quite well known example. – Slava Nov 24 '21 at 00:45
  • 4
    Does this answer your question? [Odd syntax in C++: return { .name=value, ... }](https://stackoverflow.com/questions/31594037/odd-syntax-in-c-return-name-value) (asked in 2015, so of course it doesn't mention the C++20 feature, but otherwise it looks similar) – JaMiT Nov 24 '21 at 01:10
  • @JaMiT Ah, I didn't know such thing as "gcc extensions" existed. Adding `-pedantic` generates the error messages as expected. Thank you! + @Eugene @Slave – Hakkyu Kim Nov 24 '21 at 04:43
  • @JaMiT It's my first time asking question in StackOverflow so I'm not sure what to do when a question is duplicated, should I delete it? – Hakkyu Kim Nov 24 '21 at 04:44
  • 1
    @HakkyuKim From [the help center](https://stackoverflow.com/help/duplicates): *"Some duplicate questions may eventually be deleted, but often they are left as a signpost pointing people towards the canonical answer to that question."* If you think someone else with the same question will find your post before (or instead of) the linked-to question, then you should leave it as is. – JaMiT Nov 24 '21 at 05:06

0 Answers0