17

Is this legal C++?

struct foo
{
  int a[100];
  int b[sizeof(a) / sizeof(a[0])];
};

GCC 4.6 accepts it, but MSVC 2012 doesn't. It seems like it should be fine to me, but a bit of Googling didn't help and I don't know where to look in the standard.

MSVC 2012 gives the following output:

error C2327: 'foo::a' : is not a type name, static, or enumerator
error C2065: 'a' : undeclared identifier
error C2070: ''unknown-type'': illegal sizeof operand
warning C4200: nonstandard extension used : zero-sized array in struct/union
Karu
  • 4,512
  • 4
  • 30
  • 31
  • possible duplicate of [Why I can't initialize non-const static member or static array in class?](http://stackoverflow.com/questions/9656941/why-i-cant-initialize-non-const-static-member-or-static-array-in-class) – Alok Save Sep 20 '12 at 08:32
  • 2
    Even if the ultimate cause is similar, the question looks very different to me. – Gorpik Sep 20 '12 at 08:35
  • 2
    The relevant paragraph in the C++11 standard is Clause 5, paragraph 8, I think. – jrok Sep 20 '12 at 08:41
  • @jrok: The relevant para is C++11 §12.6.2.8. – Alok Save Sep 20 '12 at 08:43

2 Answers2

18

This was illegal in C++03 because these members are nonstatic datamembers.

Starting from C++11 this is legal since in an unevaluated operand you can use nonstatic datamembers without having a corresponding object.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
1

Try this: This is a workaround for MSVC 2010 and MSVC 2012

struct Aoo
{
    typedef int ArrayType;
    ArrayType a[100];
};

struct foo : public Aoo
{   
    enum {bSize = sizeof(Aoo) / sizeof(Aoo::ArrayType)};
    int b[bSize];
};
Ram
  • 3,045
  • 3
  • 27
  • 42