3

Something like this (doesn't work):

class A {
    int arr[] = {1, 2};
};

My compiler errors out:

a.cpp:2:9: error: flexible array member 'A::arr' in an otherwise empty 'class A'
    2 |     int arr[] = {1, 2};
      |         ^~~

I guess the compiler thinks this is a flexible array (which I don't fully understand how that works).

This works fine if outside a class definition (global or local variable):

int arr[] = {1, 2};

The array has a size known at compile time (2 in this case). This is a notation used to avoid having to specify the array size since the compiler can know it by just looking at how many elements are used in the aggregate initializer. Of course I can just type in the number, but I should not have to!

Boann
  • 48,794
  • 16
  • 117
  • 146
Luiz Pontes
  • 68
  • 1
  • 4

0 Answers0