2

I know that you can initialize the whole array with initialization list like this :

struct s {
    int a[1];
    s (int b): a{b}{}
};

, but is it possible to set value of one specific member? Because this:

struct s {
    int a[1];
    s (int b): a[0]{}
};

doesn't work and throws two errors:

expected '(' before '[' token  

and

expected '{' before '[' token.
Joseph D.
  • 11,804
  • 3
  • 34
  • 67

2 Answers2

2

You can initialize an element of an array by placing the value in the appropriate position via aggregate initialization.

struct s {
    int a[2];
    s (int b): a{b, 0} {} // sets a[0] with the value of b
                          // a[1] is set to zero
};

s foo(1);  
std::cout << foo.a[0] << " " << foo.a[1]; // 1 0

UPDATE (thanks @NathanOliver)

Missing elements are zero initialized.

struct s {
    int a[2];
    s (int b): a{b} {} // a[1] is already 0
};
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
1

No. Only initializing the specialized elements of an array is supported in C, but not C++.

Note: ..., and designated initialization of arrays are all supported in the C programming language, but are not allowed in C++.

int arr[3] = {[1] = 5};        // valid C, invalid C++ (array)

You can use assignment as workaround.

struct s {
    int a[1];
    s (int b) { a[0] = b; }
};
Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405