1

I came across a source file here (in C). It uses a reasonable-but-strange style to initialize an array. I gave it a try in a shorter C++ program (please notice the "old way" in the code's comment):

arr.cc

#include <iostream>
using namespace std;

int main() {
    long arr[] = { [0] = 100, [1] = 101 }; // old way: long arr[] = { 100, 101 };
    cout << arr[0] << " " << arr[1] << endl;
}

The code is compiled like this:

g++-6 -std=c++14 arr.cc -o arr

When run, the output is this:

100 101

It passed with -std=c++14? But I can't find it in a C++ reference website, like cppreference.com. Does it conform to the standard? If so, since which version?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Leedehai
  • 3,660
  • 3
  • 21
  • 44
  • It doesn't conform, it is a GCC extension. – DeiDei May 03 '18 at 04:12
  • Compile with `-pedantic` and check the warnings. https://godbolt.org/g/rG3LXC As I said, it is an extension from the compiler vendor. – DeiDei May 03 '18 at 04:14
  • @DeiDei Just tried (`-std=c++14 -pedantic -Wall`).. it passed. FYI, my GCC is 6.3.0. – Leedehai May 03 '18 at 04:15
  • 1
    This initialization syntax is specific to C language. It is not currently supported in C++ (might be in the future). GCC allows it in C++ code as an extension. – AnT stands with Russia May 03 '18 at 04:18
  • 2
    Perhaps older GCC versions don't give out the warnings, but yeah... Designated initializers are a C feature that GCC happens to support in C++ as well. It isn't in any C++ standard. – DeiDei May 03 '18 at 04:18
  • Designated initializers are part of C99, but [they haven't made it into C++](https://stackoverflow.com/q/855996/364696). – ShadowRanger May 03 '18 at 04:24

1 Answers1

3

This is not valid C++ code; the C standard adopted it, and as an extension GCC allows it in C++ as well. To get GCC to conform to the C++ standard, you need to pass both -std=c++17 (or whatever version) and -pedantic. With that, your code does emit warnings saying it's nonstandard. The description of how this works in GCC is here.


Note that you can also do this with struct members, not just arrays; given

struct Point
{
    int x;
    int y;
};

you can say Point p = {.x = 17}. This is also nonstandard in C++ so far, but it will be adopted in C++2a. This only applies to the non-array version so far; I don't know if there are plans to add the array version as well or if it will happen by C++2a.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Daniel H
  • 7,223
  • 2
  • 26
  • 41