views:

72

answers:

2

Hi,

I've got confused by the fact that this code works:

struct S
{
  char c[];
};
S s;

According to C++ standard, chapter 8.3.4:

"If the constant expression is omitted, the type of the identifier of D is “derived-declarator-type-list array of unknown bound of T”, an incomplete object type."

But I cannot figure out how "incomplete object type" becomes complete.

Thanks for help!

A: 

It seems like this language feature is invented in order to allow the array to be initialized later in the source file. If I make c non-static, then at least on Visual Studio 2010 it fails to compile, saying that the length of c has been fixed at 0, and member redeclaration is not allowed.

// header file
struct S
{
    static char c[];
    static size_t len;
};
extern S s;

// source file
char S::c[] = "haha";
size_t S::len = (sizeof(S::c) / sizeof(S::c[0])) - 1;
rwong
+3  A: 

You've said the code you posted will compile in VS10. Turn off language extensions, and then it won't. Project>Properties>C/C++>Language>Disable Language Extensions = Yes. This is compiling because you are using a MS-specific extension to the C++ language.

In short, according to the standard, your code should not compile.

John Dibling
"When an array is used as the type of a nonstatic member all dimensions shall be specified." (9.2/8)
James McNellis
Indeed, VS2010 with /Za does not compile the code.
nyrl