4

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!

nyrl
  • 769
  • 5
  • 15
  • 1
    Welcome to SO, while asking the question you can use the buttons at the top (1010, etc) to format the code and quote parts your question correctly. – Naveen Sep 24 '10 at 11:38
  • 1
    see also http://stackoverflow.com/questions/2717671/static-arrays-defined-with-unspecified-size-empty-brackets – rwong Sep 24 '10 at 12:01
  • Great link. According to one of answers it should not compile. I've tried my code on gcc 4.4.4 (-ansi) and VC2010 and both compiled. – nyrl Sep 24 '10 at 12:21
  • 1
    Try `-pedantic` as well as `-ansi` in GCC - it leaves a lot of language extensions enabled that don't conflict with valid C++, if you don't specify `-pedantic`. – Doug Sep 24 '10 at 14:34
  • Gcc with -pedantic gives a warning of "zero sized array", but compiles – nyrl Sep 24 '10 at 16:30

2 Answers2

3

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
  • 99,718
  • 31
  • 186
  • 324
0

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
  • 6,062
  • 1
  • 23
  • 51