0

There are two arrays in my projects. One is of static const type which contain more or less entries on different projects, like

static const array_A[] = { ... };

I do not like the style of array_A[N] = { ... } since I do not want to count the length of array manually.

There is another array B whose length is required to be the same as A.

Some compiler (such as armcc) support the following trick

const int N = sizeof(array_A) / sizeof(array_A[0])
static const array_B[N];

But this trick fails with gcc compiler. So is there any other easy way ?

P0W
  • 46,614
  • 9
  • 72
  • 119
Pan Ruochen
  • 1,990
  • 6
  • 23
  • 34

1 Answers1

1

Interesting that:

int a[] = {1, 2, 3};
const int N = sizeof(a)/sizeof(a[0]);
const int b[N];

Compiles with clang, does not compile with gcc 4.2.1:

error: variably modified ‘b’ at file scope

OP asked for C, not C++, so a fix for gcc would be

int a[] = {1, 2, 3};
const int b[sizeof(a)/sizeof(a[0])];
Charlie Burns
  • 6,994
  • 20
  • 29
  • It does work. So this should be a gcc bug? – Pan Ruochen Oct 15 '13 at 06:01
  • I would not call it a gcc bug. The C language has evolved over the years, and compilers struggle to keep up and they add extensions of their own. This feature may or may not be in any C specification, I don't know. You could ask SO if this feature is found in any official C spec if you were interested. – Charlie Burns Oct 15 '13 at 15:04